[英]Nodejs Promise for custom api
我是nodejs
并且使用promise
,实际上这是我第一次使用nodejs
真正的应用。
所以我整天都在读书,我有点困惑。
这是我的模块:
function User() {
var self = this;
self.users = {};
self.start = function (user, botId) {
return new Promise(function () {
return get(user).then(function (data) {
debug(data);
if (data.botId.indexOf(botId) === false) {
return Repo.UserBotModel.addUser(user.id, botId).then(function () {
data.botId.push(botId);
return data;
});
} else
return data;
});
});
};
self.getDisplayName = function (user) {
if (user.real_name)
return user.real_name;
if (user.last_name)
return user.firstname + ' ' + user.last_name;
return user.first_name;
};
/**
* check if user exist in our database/memory cache and return it,
* otherwise insert in the database and cache it in memory and the return it
* @param user
*/
function get(user) {
return new Promise(function () {
//check if user is loaded in our memory cache
if (self.users.hasOwnProperty(user.id))
return self.users[user.id];
else {
//get from database if exist
return Repo.UserModel.get(user.id).then(function (rows) {
if (rows && rows.length) {
//user exist cache it and resolve
var data = rows[0];
if (data.botId && data.botId.length)
data.botId = data.botId.split(',');
else
data.botId = [];
self.users[user.id] = data;
//------------------------------ code execution reaches here
return data;
}
else {
//user dose not exist lets insert it
return Repo.UserModel.insert(user).then(function (result) {
return get(user);
});
}
});
}
});
}
}
我调用start
方法,然后调用私有get方法,该调用到达return data;
(标有注释),但then
函数不会在start
方法中执行?
那我在做什么错?
更新:对不起,我忘了提及我使用的是bluebird
而不是native promise
如果这样做有所不同?
您不能从Promise
构造函数中return
-您必须调用resolve
(预期会异步发生)。 您根本不需要在这里使用Promise
构造函数 。 您可以忽略它,它应该可以工作。
Repo.UserModel
的方法已经返回promise,因此您不必使用new Promise
创建新的方法。 then
读取这些承诺中的值。 then
还提供了一种转换承诺的方法。 如果您在传递给函数的返回值then
, then
会返回一个新的承诺,包装你的返回值。 如果这个值是一个承诺,它将等待着。 Promise.resolve
。 知道了,你可以简化get
就像这样:
function get(user) {
if (...) {
return Promise.resolve(...)
} else {
return Repo.UserModel.get(...).then(function(rows) {
...
return ...
})
}
}
此版本的get
始终会返回一个可以按如下方式使用的承诺:
get(...).then(function(resultOfGet) {
// process resultOfGet
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.