![](/img/trans.png)
[英]use forEach() with promises while access previous promise results in a .then() chain?
[英]Access to data from a previous Promise in a chain
我的問題是我想訪問從先前的then()獲取的數據,我該怎么辦? (要求:我無法修改externalBuiltInFunction())
ajaxCall(...)
.then( (response) => {
return response.json();
})
.then ( (jsonData) => {
return externalBuiltInFunction(jsonData);
})
.then ((dataFromExternalFunction) => {
... here i want to use jsonData, how can i do ?...
}
謝謝你的幫助
您可以在async/await
僅使用一個then
語句:
ajaxCall(...)
.then(async response => {
const jsonData = await response.json();
const external = await externalBuiltInFunction(jsonData);
// Here you still have access to jsonData and external
})
您可以將jsonData
存儲在外部詞法環境中的變量中:
let jsonData;
ajaxCall(...)
.then( (response) => {
return response.json();
})
.then ( (jsonData) => {
jsonData = jsonData;
return externalBuiltInFunction(jsonData);
})
.then ((dataFromExternalFunction) => {
// jsonData is available here
}
或者,您可以將jsonData
傳遞給下一個jsonData
, jsonData
將其作為數組進行顯式傳遞.then
並調用externalBuiltInFunction
:
ajaxCall(...)
.then( (response) => {
return response.json();
})
.then ( (jsonData) => {
return Promise.all([externalBuiltInFunction(jsonData), jsonData]);
})
.then (([dataFromExternalFunction, jsonData]) => {
// jsonData is available here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.