roger
roger

Reputation: 9913

how to make node promise method sync?

I want to do some prepare work, and my other work should start after these is done, so I call these work by Q.all, but some work is async, this is what I want.

May be my code will make you understand me, in this simple example I want to do this:

  1. call foo2 for item in array
  2. in foo2, I wait 10 * a ms(assume this to be some completed work), and change res.
  3. I want to foo2 is running over then console.log(res), this means all wait is over and all item is added to res. So in my example, res is change to 6.

Here is the code

var Q = require("q");
var res = 0;
function foo(a) {
  res += a;
}

function foo2(a) {
  // this is a simple simulation of my situation, this is not exactly what I am doing. In one word, change my method to sync is a little bit difficult
  return Q.delay(10 * a).then(function() {
    res += a;
  });
}

// Q.all([1, 2, 3].map(foo)).done(); // yes, this is what I want, this log 6

// however, because of some situation, my work is async function such as foo2 instead of sync method.
Q.all([1, 2, 3].map(function(a) {
  return foo2(a);
})).done();
console.log(res); // I want 6 instead of 0

Upvotes: 0

Views: 308

Answers (1)

Ludovic C
Ludovic C

Reputation: 3065

You are mixing sync and async style of programming.

In this case, your console.log statement will be run before any promise had time to fulfill (before res was modified by them), as it it not inside a promise block.

See here how console.log will be run after promises have been resolved

var Q   = require("q"),
    res = 0;


function foo(a) { res += a; }

function foo2(a) {
  return Q
    .delay(10 * a)
    .then(function() { res += a; });
}

Q.all( [1, 2, 3].map(function(a) { return foo2(a); }) )
.then(function(){ console.log(res) })
.done();

Upvotes: 1

Related Questions