访问链中先前 Promise 的数据

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 ?...
}

感谢帮助

您可以将jsonData存储在外部词法环境的变量中:

let jsonData;

ajaxCall(...)
    .then( (response) => {
        return response.json();
    })
    .then ( (jsonData) => {
        jsonData = jsonData;
        return externalBuiltInFunction(jsonData);
    })
    .then ((dataFromExternalFunction) => {
        // jsonData is available here
    }

或者,您可以将 jsonData 作为数组显式传递给下一个 .then,结果为 externalBuiltInFunction 调用:

ajaxCall(...)
    .then( (response) => {
        return response.json();
    })
    .then ( (jsonData) => {
        return Promise.all([externalBuiltInFunction(jsonData), jsonData]);
    })
    .then (([dataFromExternalFunction, jsonData]) => {
        // jsonData is available here
    }

您可以只使用一个 then 语句与 async/await:

ajaxCall(...)
  .then(async response => {                          
    const jsonData = await response.json();
    const external = await externalBuiltInFunction(jsonData);
    // Here you still have access to jsonData and external 
  })