Post çağrısı için bir istek oluşturmak için başka bir çağrıdan yanıt nasıl beklenir

0

Soru

Aşağıda 2 dosyam var, aramanın düzgün olduğundan emin olmak istiyorum. Sözü ve geri aramayı denedim, itiraf etmeliyim ki, zaman uyumsuz çağrılara %100 aşina değilim.

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;

roller.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;

Fetch'i aradığımda nasıl emin olabilirim('www.example.com/auth', seçenekler), seçenekler.ceset tanımlanmamış mı? Async / await ve callback'leri kullanmaya çalıştım, hiçbir şey benim için işe yaramıyor.

Herhangi bir yardım çok takdir edilecektir.

Teşekkürler

1

En iyi cevabı

0

Endişeye gerek yok - ilk başta söz almak kolay değil. Peki, ilk olarak, tek değer güveniyor, eğer giderilmiş olduğunu beklemiş olabilir. Bu, daha önce de belirttiğiniz gibi yapılabilir .sonra veya async / await ile.

.sonra-çözüm:

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

async-await-çözümü:

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

Lütfen callermethod'un bir Sözü tekrar geri getireceğini unutmayın, çünkü eşzamansızdır.

2021-11-23 07:44:07

callerMethod gibi başka bir yöntem oluşturmamanın bir yolu var mı? Rol değiştirmek gibi.yapılandırmada js veya getAuth.js
Tian Qin

Evet, işe yarayabilir .sonra ve .istersen yakala. Bu yüzden birçok geliştirici tüm kod tabanı üzerinden async kullanıyor
Marcel Cremer

Ben denedim ekleyin .sonra ve .getauth'u yakala, bu işe yaramıyor..Ve her şey bir kurucuya sarılmış, kurucuya async koyamıyorum..
Tian Qin

Diğer dillerde

Bu sayfa diğer dillerde

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