1

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?

Sato
  • 8,192
  • 17
  • 60
  • 115

3 Answers3

5

If you don’t need to use status in C and D, this use of .then will result in a promise that resolves to task:

getStatus()
    .then(updateStatus)
    .then(() => getTask())
    .then(updateTask)

There’s also async/await:

const status = await getStatus();
await updateStatus(status);

const task = await getTask();
await updateTask(task);
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

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 ;)

v-andrew
  • 21,939
  • 6
  • 36
  • 41
  • How to get status returned by `getStatus` in `D`? – Sato Apr 04 '17 at 03:41
  • @Sato, that's something extra that was not asked in the question. A range of solutions is offered [here](http://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain/). Your nested approach is probably the best solution. Just remember to add some returns. – Roamer-1888 Apr 04 '17 at 08:32
  • @Sato just return it in `D` and it will be available to the next `.then( function(status){/*status available here*/})` – v-andrew Apr 04 '17 at 12:54
0

If you want to get status returned by getStatus in D . you can do like this

function getStatus ( //here return promise)
function updateStatus( //here return promise)
function updateTask( //here return promise) 

after this

Promise.all([
    getStatus(),updateStatus(),updateTask() 
]).spread(function(a, b,c) {
   //here a = result of getStatus
   //here b = result of updateStatus
   //here c = result of updateTask
});
AJS
  • 953
  • 7
  • 21