Jake Wilson Jake Wilson - 1 month ago 5
Node.js Question

How to structure nested Promises

I have a situation where I think the only choice for me is to nest some Promises within each other. I have a Promise that needs to be performed and a method that does something until that Promise is complete. Something like this:

let promise = new Promise((resolve, reject) => {

// Do some stuff

});

doSomethingUntilPromiseisDone(promise);


However, within my Promise, I need to execute another method that returns another Promise:

let promise = new Promise((resolve, reject) => {

fetchValue(url)
.then((value) => {

// Do something here

}).catch((err) => {
console.error(err);
});

});

doSomethingUntilPromiseisDone(promise);


But now, in the
fetchValue
method's
then
statement, I have another method I need to execute that, guess what, returns another Promise:

let promise = new Promise((resolve, reject) => {

fetchValue(url)
.then((value) => {

saveToCache(value)
.then((success) => {

console.log('success!!');
resolve('success');

});

}).catch((err) => {
console.error(err);
});

});

doSomethingUntilPromiseisDone(promise);


So in the end, I have a Promise, within a Promise, within a Promise. Is there someway I can structure this better so that it is more straightforward? It seems like nesting them within each other is counter to Promise's intended chaining approach.

Answer

Use .then()

let doStuff = (resolve, reject) => {/* resolve() or reject() */};
let promise = new Promise(doStuff);
doSomethingUntilPromiseisDone(
  promise 
  .then(value => fetchValue(url))
  .then(value => value.blob())
  .then(saveToCache)
)
.then(success => console.log("success!!"))
.catch(err => console.error(err))