【发布时间】:2016-04-19 15:04:47
【问题描述】:
我是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,如果这有什么不同?
【问题讨论】:
-
getDisplayName应该是user的方法,或者是静态函数。 -
您应该将 Promise 本身缓存在
users中,而不是data值 - 请参阅 here 示例
标签: javascript node.js promise bluebird