使用node.js,通过promise而不是回调,通过指定用户id从mongo检索用户对象。数据库访问使用 require('mongodb').Db
。
调用从以下代码的底部开始:findByIdPromise(userId)
collection.findOne()
需要 userId 作为参数,但 then()
调用一个以 Promise 作为单个参数的函数。
为了解决这个限制,我传递了 then()
一个具有 userId 属性预设的对象 finder
和一个接受集合的函数 findUser
Promise,并调用集合的 findOne
,向其传递预设的 userId。
这是一个半体面的方法吗?
UserProvider.prototype.getCollectionPromise = function () {
var deferred = q.defer();
var resolve = deferred.resolve;
var collectionCallback = function (error, usersCollection) {
if (error) {
throw new Error(error);
} else {
resolve(usersCollection);
}
};
this.db.collection(CollectionName, collectionCallback);
return deferred.promise;
};
UserProvider.prototype.findOnePromise = function () {
var userId;
var setUserId = function (id) { this.userId = id; };
var deferred = q.defer();
var resolve = deferred.resolve;
var findUser = function (coll) {
coll.findOne(
{ _id: id },
function(error, result) {
if (error) {
throw new Error(error);
} else {
resolve(result);
}
}
);
};
return deferred.promise;
};
UserProvider.prototype.findByIdPromise = function(id) {
var finder = new UserProvider.findOnePromise();
finder.setUserId(id);
return this.getCollectionPromise().then(finder.findUser);
};
最佳答案
在 Node.js 中执行异步工作的标准方法是通过回调,通常是函数的最后一个参数,它将错误作为其第一个参数,并将任何后续参数作为返回值。这是由标准库(即内置包)以及大多数使用这种风格的流行 npm 模块制定的标准。
当然,如果您愿意,我们完全欢迎您使用 Promise。不过,我建议不要这么做;您最终将包装几乎所有您使用的库,以便将其从回调转换为 promise ,这不会是一个特别有趣的练习。
注意:据我所知,唯一使用 Promise 并且相当流行的异常(exception)是 selenium-webdriver
。据我所知,它使用了 Promise,因此使用它编写的代码看起来与其他 selenium 库尽可能相似,它们都是同步的。
关于Node.js、mongo、promise - 将参数传递给 then 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20509026/