Tuesday, 23 May 2017

Nested Promise Chain Handling? (Promise.then( new Promise))?

How Can I Handle promise in promise?

sql stands for Sequelize.

asyncFunc1                 //(sql.findOne)
.then(
  (res1)=>asyncFunc2(res1) //(sql.findOrCreate - must end with spread)
  .spread(
      (res2)=>{            // **Must** Use asyncFunc2's Result value.
         var newAsyncFunc = Promise.resolve(res2);
         return Promise.all(newAsyncFunc)
      }
      .then(() => asyncFunc3(res1,res2)) //(sql.findOrCreate)
  ))                       // **Must** Use asyncFunc1, 2's Result value.
.spread((res3) => asyncFunc4(res3);

Why I nested .then(() => asyncFunc3(res1,res2)) under (res2)=>{} is to pass res2 value over next function.

And What I want to achieve is, I really want to run .then(() => asyncFunc3(res1,res2)) this right after return Promise.all(newAsyncFunc).

So The running sequence will be like asyncFunc -> asyncFunc2 -> Promise.all(newAsyncFunc) -> .then(asyncFunc3) -> asyncFunc4

But this code works like this. asyncFunc -> asyncFunc2 -> asyncFunc3 -> asyncFunc4 ........(far after)-> Promise.all(newAsyncFunc)

What's the problem with my code? why this code doesn't chained as I wanted?

(sorry for my js coding.. I'm newbie here)



via Daniel T. Lee

No comments:

Post a Comment