简体   繁体   English

访问链中上一个Promise中的数据

[英]Access to data from a previous Promise in a chain

my problem is I want access to data fetched from a previous then(), how can i do it ? 我的问题是我想访问从先前的then()获取的数据,我该怎么办? (requirement : I cannot modify externalBuiltInFunction() ) (要求:我无法修改externalBuiltInFunction())

ajaxCall(...)
.then( (response) => {                          
    return response.json();
})
.then ( (jsonData) => {
    return externalBuiltInFunction(jsonData);
})
.then ((dataFromExternalFunction) => {
   ... here i want to use jsonData, how can i do ?...
}

Thx for the help 谢谢你的帮助

You could use just one then statement with async/await : 您可以在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 
  })

You can store jsonData in a variable in the outer lexical environment: 您可以将jsonData存储在外部词法环境中的变量中:

let jsonData;

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

Alternatively, you can pass jsonData to the next .then explicitly as an array with result of externalBuiltInFunction call: 或者,您可以将jsonData传递给下一个jsonDatajsonData将其作为数组进行显式传递.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM