Cum să așteptați pentru răspunsul de la alte sunați pentru a crea o cerere de apel post

0

Problema

Am 2 fisiere de mai jos, vreau să mă asigur că apelul este în ordine. Am încercat promisiunea și de apel invers, trebuie să recunosc, eu nu sunt 100% familiarizat cu async apeluri.

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;

Cum pot fi sigur că, atunci când sunt de asteptare aduce('www.example.com/auth', opțiuni) opțiuni.corpul nu este nedefinit? Am încercat să folosească asincron/așteaptă și callback, nimic nu funcționează pentru mine.

Orice ajutor va fi foarte apreciat.

Multumesc

1

Cel mai bun răspuns

0

Nu vă faceți griji - promisiuni nu sunt ușor pentru a obține de la început. Deci, în primul rând, vă puteți baza doar pe valoare, dacă ai așteptat că ea a fost rezolvată. Acest lucru poate fi făcut, după cum am subliniat deja, cu .apoi sau cu async / așteaptă.

.apoi-soluție:

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

asincron-așteaptă-soluție:

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

Vă rugăm să rețineți, că callerMethod va returna o Promisiune din nou, pentru că este asincron.

2021-11-23 07:44:07

Există o modalitate de a nu crea o altă metodă ca callerMethod? Cum ar fi schimbarea în roles.js sau getAuth în config.js
Tian Qin

Da, ai putea folosi .atunci și .prinde acolo, dacă vrei. Acesta este motivul pentru mulți devs utilizarea asincron prin tot codebase
Marcel Cremer

Am încercat să-l adăugați .atunci și .prinde în getAuth, acest lucru nu este de lucru..Și totul este învelit într-un constructor, eu nu pot pune asincron pe constructor..
Tian Qin

În alte limbi

Această pagină este în alte limbi

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