简体   繁体   中英

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 ? (requirement : I cannot modify 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 :

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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