하는 방법에서 응답을 기다리는 다른 통화를 만드는 요청에 대한 후 통화

0

질문

나는 아래 2 개의 파일로 되어 있는지 확인하려면 전화를 위해서입니다. 나 약속과 콜백,나는 것을 인정해야,나는 100%에 익숙한 비동기 호출합니다.

config.js:

import rolesJson from '../../roles';

class Config{

url;
rolesList;

constructor(callback){

    var baseurl = 'www.example.com/env';

    fetch(baseurl)
        .then(response => response.json())
        .then(data => {
            this.url = data.url;
            getAuth(data.env);
    }).catch((error) => {

    });

    const getAuth= (env) => {
        const headers = { 'Content-Type': 'application/json' };
        const options = { method: 'POST', headers, body:JSON.stringify(rolesJson(env))};
        console.log("THIS BODY SHOULD NOT BE UNDEFINED", options.body);
        fetch('www.example.com/auth', options)
            .then(response => response.json())
            .then(data => {

            }).catch((error) => {

            });
    };
}    
}
module.exports = Config;

roles.js

var roleUrl = 'www.example.com/roles';

const setEnviroment = (rolesdata,env) => {
let reqBody = {
    "environment": env,
    "components": rolesdata
}
console.log("REQUEST BODY CREATED", reqBody);
return req;
}

const getRoles = (env) => {
fetch(roleUrl)
.then(response => response.json())
.then(roles => {
    let rolesList = [];
    roles.map(x => {
        const roleObj = {
            name: x.name,
            id: x.id,
        }
        rolesList.push(roleObj);
    })
    return setEnviroment(rolesList, env);
 }).catch((error) => {

});
};
module.exports = getRoles;

고 있는지 어떻게 확인할 수 있을 때 호출하면 가져올('www.example.com/auth'옵션)옵션.몸이 정의되지 않은? 가 사용하는 비동기/여과 콜백하지 않습니다.

어떤 도움이 될 것이 매우 감사합니다.

감사

1

최고의 응답

0

걱정-약속을 쉽게 얻을 수 없습니다. 그래서 최초의 모든,당신은에 의존 할 수 있는 가치는 경우,당신을 기다렸다는 그것이 해결되었습니다. 이 작업을 수행 할 수 있습니다,당신은 이미 지적했다.다음 또는 async/기다리고 있습니다.

.그런 다음 솔루션:

var roleUrl = 'www.example.com/roles';

const setEnviroment = (rolesdata,env) => {
let reqBody = {
    "environment": env,
    "components": rolesdata
}
console.log("REQUEST BODY CREATED", reqBody);
return req;
}

const getRoles = (env) => {
fetch(roleUrl)
.then(response => response.json())
.then(roles => {
    let rolesList = [];
    roles.map(x => {
        const roleObj = {
            name: x.name,
            id: x.id,
        }
        rolesList.push(roleObj);
    })
    return setEnviroment(rolesList, env);
 });
 // we return the promise
};
module.exports = getRoles;
class Config{

url;
rolesList;

constructor(callback){

    var baseurl = 'www.example.com/env';

    fetch(baseurl)
        .then(response => response.json())
        .then(data => {
            this.url = data.url;
            getAuth(data.env);
    }).catch((error) => {

    });

    const getAuth= (env) => {
        const headers = { 'Content-Type': 'application/json' };
        const options = { method: 'POST', headers, body:JSON.stringify(rolesJson(env))};
        console.log("THIS BODY SHOULD NOT BE UNDEFINED", options.body);
        fetch('www.example.com/auth', options)
            .then(response => response.json());
        // we return the Promise
    };
}    
}
module.exports = Config;
// calling method

Config.getAuth(env).then((value) => {
    return getRoles(env); //this returns a Promise again
}).then(x => {
    // here you have the return type of getRoles
})

비동기 처리 솔루션:

var roleUrl = 'www.example.com/roles';

const setEnviroment = (rolesdata,env) => {
let reqBody = {
    "environment": env,
    "components": rolesdata
}
console.log("REQUEST BODY CREATED", reqBody);
return req;
}

const getRoles = async (env) => {
    let response await fetch(roleUrl); // awaiting fetch promise
    let roles = await response.json(); // awaiting .json()-promise
    let rolesList = [];
    roles.map(x => {
        const roleObj = {
            name: x.name,
            id: x.id,
        }
        rolesList.push(roleObj);
    })
    return setEnviroment(rolesList, env);
 };
 // async always returns a promise

module.exports = getRoles;
class Config{

url;
rolesList;

constructor(callback){

    var baseurl = 'www.example.com/env';

    fetch(baseurl)
        .then(response => response.json())
        .then(data => {
            this.url = data.url;
            getAuth(data.env);
    }).catch((error) => {

    });

    const getAuth = async (env) => {
        const headers = { 'Content-Type': 'application/json' };
        const options = { method: 'POST', headers, body:JSON.stringify(rolesJson(env))};
        console.log("THIS BODY SHOULD NOT BE UNDEFINED", options.body);
        const response = await fetch('www.example.com/auth', options);
        const body = await response.json();
        return body; // we return a Promise including the body
    };
}    
}
module.exports = Config;
// calling method

const callerMethod = async () => {
    const auth = await Config.getAuth(env);
    const roles = await getRoles(env);
    //now you can work with the resolved stuff
};

는 것을주의하시기 바랍 callerMethod 이 반환됩니다 약속을 다시 자체이기 때문에,그것은 async.

2021-11-23 07:44:07

방법은 없을 만들지 않는 다른 방법은 다음과 같 callerMethod? 다음과 같이 변화에 roles.js 또 getAuth 에 config.js
Tian Qin

예로 사용할 수 있습니다.다음과.catch 할 수 있습니다. 이 때문에 많은 devs 사용하여 비동기를 통해 전체 codebase
Marcel Cremer

나도 추가 할 수 있습니다.다음과.catch 에 getAuth,이것은 작동하지 않고 이 모든 일에 싸여 생성자,나를 넣어 비동기에 생성자..
Tian Qin

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................