[英]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.