Jak się doczekać odpowiedzi od innego połączenia, aby utworzyć kwerendę na wywoływanie

0

Pytanie

Mam poniżej 2 plików, chcę się upewnić, że połączenie jest w porządku. Próbowałem obietnica i oddzwanianie, muszę przyznać, że nie jestem na 100% zna silników asynchronicznych wywołań.

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;

Jak mogę być pewien, kiedy dzwonię fetch('www.example.com/auth', opcje), opcje.ciało nie jest niepewna? Próbowałem użyć asynchroniczne/czekam i wywołania zwrotne, dla mnie nic nie działa.

Każda pomoc będzie bardzo wdzięczna.

Dziękuję

1

Najlepsza odpowiedź

0

Nie martw się - obietnice nie jest tak łatwo dostać na początku. Dlatego, przede wszystkim, można polegać tylko na wartość, jeśli oczekujesz, że będzie ono ustalone. Można to zrobić, jak już wskazywaliśmy, z pomocą .następnie lub z asynchronicznym / oczekiwaniem.

.następnie-rozwiązanie:

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
})

asynchroniczne oczekiwanie rozwiązania:

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
};

Proszę zwrócić uwagę, że callerMethod ponownie zwróci sama obietnica, bo ja asynchronicznie.

2021-11-23 07:44:07

Czy istnieje sposób, aby nie tworzyć inne metody, takie jak callerMethod? Jak ubieranie się w roles.js lub uzyskać dostęp do config.js
Tian Qin

Tak, że może ci się to przydać .i wtedy ... łap tam, jeśli chcesz. Dlatego wielu programistów korzysta z niejednoczesności w całym kodzie
Marcel Cremer

Próbowałem dodać .następnie .złap w getAuth, to nie działa..A wszystko to opakowane w konstruktorze, nie mogę włączyć niejednoczesności do konstruktora.
Tian Qin

W innych językach

Ta strona jest w innych językach

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