In this tutorial, you’ll learn how to access promise result in .then promise chain. In nested JavaScript Promise, sometimes it’s required to access one promise result in the promise chain. In such cases, you tend to assign promise result to a variable and then access it in promise chain.
Let’s have a look at how you can access promise results in the entire chain.
function getPromise(i){
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve({"data" : i});
}, 2000);
})
}
function queryPromiseChain(){
let promiseOneResult;
let promiseTwoResult;
getPromise(1)
.then(function(result){
promiseOneResult = result.data;
return getPromise(result.data + 1)
})
.then(function(result){
promiseTwoResult = result.data;
return getPromise(result.data + 1)
})
.then(function(result){
console.log('First result ', promiseOneResult);
console.log('Second result ', promiseTwoResult);
console.log('Third result ',result.data);
})
}
queryPromiseChain();
As seen in the above code, you can simply define a variable to store the result of each promise chain and then access it where ever you want inside the promise chain.