3 回答
TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
您使用不當(dāng)。您需要等待。解決這兩個(gè)承諾后,響應(yīng)數(shù)據(jù)將位于您從 中獲取的每個(gè)響應(yīng)對(duì)象內(nèi)部的一個(gè)屬性中。如果你需要整個(gè)響應(yīng)對(duì)象,那么你可以解構(gòu)它async-awaitPromise.alldataaxios
下面是一個(gè)示例
const FetchData = async (): Promise<{ run: string; app: string }> => {
try {
const [response1, response2] = await Promise.all([
axios({
...
}),
axios({
...
})
]);
return {
run: response1,
app: response2
};
} catch (error) {
console.log(error);
}
};
下面是一個(gè)從 json 占位符 API 的 2 個(gè)終結(jié)點(diǎn)獲取數(shù)據(jù)的演示
TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
您需要更改返回語(yǔ)句的位置:
更新了代碼并進(jìn)行了更改:
const FetchData = (): Promise<{ run: string; app: string }> => {
let aToken:string;
let bToken:string;
// Return the promise here
return Promise.all([
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({
'grant_type': 'client_credentials'
}, {
'scope': 'run:crud'
}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
}),
axios({
method: 'post',
url: 'https://oauth2.-arch.mand.com/oauth2/token',
data: qs.stringify({
'grant_type': 'client_credentials'
}, {
'scope': 'exe:crud'
}),
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
'Content-Type': 'application/x-www-form-urlencoded',
}
})
]).then(axios.spread((...responses: AxiosResponse[]) => {
aToken = responses[0];
bToken = responses[1];
// This return is for getting the data once the promise is resolved either with then or await
return {
run: aToken ,
app: bToken
};
}).catch(function(error: any) {
console.log("Error: " + error);
return error;
});
)}
由于您在承諾解決之前返回值,因此您不會(huì)獲得任何數(shù)據(jù)。您需要返回 promise,然后您需要返回所需的數(shù)據(jù),以便在調(diào)用函數(shù)中解析 promise 后獲取。
TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
const res = await Promist.all([...])
return { run: res[0], app: res[1] }
添加回答
舉報(bào)
