【发布时间】:2015-10-21 11:02:00
【问题描述】:
这有点复杂。让我们显示代码:
requestAccessToken().then(function(requestResult) { // this is the first then()
if(requestResult.ok == 1) {
return document;
}
}).then(function(document) { // this is the second then()
return db.update(updateArgu); // here, db.update will return a promise obj
}).then(function(result) { // this is the last then()
console.log('update ok');
console.log(result);
});
由于db.update(updateArgu)会返回一个promise对象,它可以像db.update().then()一样添加一个.then()方法。
但我想保持主链像requestAccessToken().then().then(),所以我在第二个then() 中返回了db.update()。输出是:
app-0 update ok
app-0 undefined
db.update 代码是:
exports.update = function(arguments) {
var name = arguments.name;
var selector = (arguments.selector) ? arguments.selector : {};
var document = (arguments.document) ? arguments.document : {};
var options = (arguments.options) ? arguments.options : {};
return Promise(resolve, reject) {
MongoClient.connect(DBURL, function(err, db) {
if(err) throw err;
db.collection(name).update(selector, document, options, function(err, result) {
db.close();
if(err) {
reject(err);
} else {
resolve(result);
}
});
});
}
}
你可以看到它有resolve(result),如何转移到最后一个then()?
【问题讨论】:
-
它被转移到最后一个
then回调,否则根本不会被调用。只是result是undefined。不是吗?您期望 Collectionupdate方法返回什么? -
在你的 MongoClient 回调中加入一个 console.log 看看结果如何。你也想返回一个“新的承诺”
-
@Bergi 是的,最后一个
then()被调用,但没有result -
return Promise()应该是return new Promise()。 -
@BrickYang:我的意思是
result已经在db.update回调中未定义。你在那里检查过吗?这似乎不是一个承诺问题。
标签: node.js asynchronous promise