[英]Wrong executing order with NodeJS callback based function in promise chain
我正在尝试在Promise链中使用回调函数。 实际上,原始代码分为两个文件,并且包含更多代码,但是为了清楚地说明问题,我将其简化为一个简单文件。
我期望产生以下代码:ABCDEF,但我得到:ADBECF。我不明白为什么D在B之前被调用,以及如何使代码按预期工作!
当我不调用任何基于回调的函数而仅使用Q.async函数时,它就会按预期工作!
这是代码:
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');
}
));
任何帮助表示赞赏。 谢谢。
问题是您如何致电doSomething
此代码应按您需要的顺序工作
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');
});
像doSomething()
这样使用doSomething会立即执行它,而.then(
会因为它不是一个函数而忽略它... doSomething
一个参数就是一个函数... doSomething()
作为参数是结果。功能
由于我不完全了解doSomething
函数内容的语义,因此上述内容可能实际上无效,因此我无法测试该特定代码
我假设doSomething返回一个值或一个Promise
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.