Monday, 3 April 2017

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?



via Sato

No comments:

Post a Comment