Quip456
Quip456

Reputation: 3

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

Upvotes: 0

Views: 106

Answers (2)

antonku
antonku

Reputation: 7665

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
    }

Upvotes: 1

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

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 
  })

Upvotes: 2

Related Questions