Search code examples
javascriptnode.jspromisebluebird

How to use promise to do serial tasks?


So I have 4 tasks: getStatus(), updateStatus(A), getTask(), updateTask(), it should be executed in this way:

getStatus(function(status) {
  // A
  updateStatus(status, function(status) {
    // B
    getTask(function(task) {
      // C
      updateTask(task, function(task) {
        // D
      })
    })
  })
})

So in order to avoid callback hell, I used promise, now all these four tasks return a Promise, then I changed it to this way

getStatus().then(function(status) {
  // A
  updateStatus(status).then(function(status) {
    // B
    getTask().then(function(task) {
      // C
      updateTask(task).then(function(task) {
        //D
      })
    })
  }) 
}) 

As you can see, it still has then hell,

Am I doing something wrong with Promise?


Solution

  • It should be something like:

    getStatus().then(function(status) {
      // A
       return updateStatus(status)
    }).then(function(status){
       return updateStatus(status)
    }).then(function(status) {
      return getTask()
    }).then(function(task) {
          // C
      return updateTask(task)
    }).then(function(task) {
         //D
        return getStatus();
    }).then(function(newStatus){
         // here you have newStatus returned by getStatus() in D
    })
    

    And there is no call back hell anymore ;)