Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serial execution with Q promises

Tags:

javascript

q

I think I'm misunderstanding how Q promises work. I want my first promise to resolve before the next one starts, but that's not happening. Here is my code:

var Q = require('q');

function doWork(taskName) {
  var deferred = Q.defer();
  console.log('starting', taskName);
  setTimeout(function() { 
    console.log('done with', taskName);
    deferred.resolve(); 
  });

  return deferred.promise;
}

doWork('task one')
  .then(doWork('task two'))
  .then(function() { console.log('all done'); });

This code produces:

$ node test.js 
  starting task one
  starting task two
  done with task one
  done with task two
  all done

I would hope that it produces:

$ node test.js 
  starting task one
  done with task one
  starting task two
  done with task two
  all done

What am I doing wrong?

like image 451
Nick Heiner Avatar asked Mar 11 '13 23:03

Nick Heiner


2 Answers

This works:

doWork('task one')
  .then(function() {
    return doWork('task two')
  })
  .then(function() {
    console.log('all done'); 
  });

That makes sense - just calling doWork directly in then() will fire off the timeout immediately, instead of giving Q a chance to wait until task one is complete.

like image 117
Nick Heiner Avatar answered Sep 28 '22 17:09

Nick Heiner


The reason is that the doWork needs to be referenced as a function. If you want to reference a function inside the '.then' then you just give the function name, you don't pass the parameters. When the parser sees .then(doWork('taskTwo'))it will run doWork('taskTwo') BEFORE the .then is even evaluated. It's trying to bind the function parameter.

In this case, if you return the parameter for the next task in the resolved promise of the previous task then the parser will call doWork with the correct parameter and in the correct order.

var Q = require('q');
function doWork(taskNum) {
    var deferred = Q.defer();
    console.log('starting', taskNum);
    setTimeout(function() { 
      console.log('done with task', taskNum);
      deferred.resolve(++taskNum); 
    });

    return deferred.promise;
}

doWork(1)
.then(doWork)
.then(function(lastTaskNum) { console.log('all done'); });
like image 20
Daniel Byrne Avatar answered Sep 28 '22 18:09

Daniel Byrne