alfredopacino
alfredopacino

Reputation: 3241

Chaining a series of Promises

I need to execute a bunch of 'promisified' function sequentially (I mean synchronously, since in each one needs the result of the previous one). This code prints bar1bar0 while I expect bar0bar1.

function _setTime(str) {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve(`bar${str} `);
      }, 1);
    });
}
_setTime("0")
    .then(function(str) {
        return _setTime("1"+str)
  })
  .then(function(str) {
        console.log(str)
  })

Upvotes: 1

Views: 47

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138267

A workaround:

 _setTime("0").then(function(str) {
    return _setTime("1").then(res=>str+res)
 })
.then(function(str) {
    console.log(str)
})

Upvotes: 2

JDB
JDB

Reputation: 25810

The code is functioning correctly and is being handled "synchronously"... you just have a bug in how you are calling your function:

The first setTime("0") "returns" "bar0"

You then call setTime("1" + "bar0") which "returns" "bar" + "1bar0"

Your newer strings are being prepended rather appended.

Upvotes: 5

Related Questions