Domanda

I want to separate my code logic. And the long chain is somewhat difficult to be controlled by condition.

I wrote a test code:

var Q, f, p;

Q = require('q');

f = function(t, info) {
  var deferred = Q.defer();
  setTimeout(function() {
    console.log(info);
    return deferred.resolve();
  }, t);
  return deferred.promise;
};

p = f(500, 0);

p.then(function() {
  return f(300, 1);
});

p.then(function() {
  return f(100, 2);
});

I hope the result to be:

0
1
2

But I always get:

0
2
1

Is there anything that I am doing wrong?

È stato utile?

Soluzione 2

You need to chain the promises:

p = f(500, 0);

p = p.then(function() {
  return f(300, 1);
});

p = p.then(function() {
  return f(100, 2);
});

Or more idiomatic:

f(500, 0).then(function() {
  return f(300, 1);
}).then(function() {
  return f(100, 2);
});

Altri suggerimenti

You must chain the then so that then is called on the returned promise :

p = f(500, 0);
p.then(function() {
  return f(300, 1);
}).then(function() {
  return f(100, 2);
});

There's no problem in passing a promise, that's what you already do (f returns a promise).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top