简体   繁体   中英

Wrong executing order with NodeJS callback based function in promise chain

I'm trying to use a callback function in a promise chain. Actually the original code is divided into two files and contains a lot more code, but to make the problem clear I've simplified it into one simple file.

I'm expecting the following code to produce: ABCDEF, but instead I get: ADBEC F. I can't understand why D gets called before B, and how to make the code work as expected!

When I'm not calling any callback based function and just use Q.async functions then it is working as expected!

Here is the code:

var Q = require('q');
var FlakeId = require('flake-idgen');
var biguint = require('biguint-format');
var flakeIdGen = new FlakeId({ id: 0, epoch: 1234567891234 });
var idDec = null;

var deferred = Q.defer();
var createId = function() {
  console.log('A');
    flakeIdGen.next(function (err, id) {
      console.log('B');
      if (err) {
        console.log('Error 1');
        deferred.reject(new Error(err));
      } else {
        idDec = biguint(id, 'dec');
        deferred.resolve(idDec);
      }   
    }); 
  return deferred.promise;
};

var doSomething = Q.async(function* () {
  console.log('D');
});

createId().then(function(idDec) {
    console.log('C');
  }).fail(function(err) {
    console.log('Error 2');
}).then(
doSomething().then(function() {
    console.log('E');
  }).fail(function(err) {
    console.log('Error 3');
}).then(function() {
  console.log('F');
  }
));

Any help appreciated. Thanks.

the issue is how you are calling doSomething

This code should work in the order you need

createId()
.then(function(idDec) {
    console.log('C');
})
.fail(function(err) {
    console.log('Error 2');
})
.then(function() { // edited as per comments
    return doSomething(p1, p2);
})
.then(function() {
    console.log('E');
}).fail(function(err) {
    console.log('Error 3');
}).then(function() {
    console.log('F');
});

using doSomething like doSomething() will execute it immediately, and the .then( will ignore it as it isn't a function ... doSomething a an argument is a function ... doSomething() as an argument is the result of the function

As I am not fully conversant with the semantics of the contents of doSomething function, the above may not actually work, I have no way to test that specific code

I assume that doSomething returns either a value or a Promise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM