【发布时间】:2018-07-19 00:30:13
【问题描述】:
我刚刚开始节点并且来自 PHP 背景。一段时间以来,我一直试图弄清楚 Promise,但无法弄清楚。
我试图在循环中的第二个查询中使用一个查询的结果,但有两个问题:
-ONE:typeof 值显示一个对象;但是当我安慰它时,它显示未定义
-二:我的结果没有按正确的顺序排列。我正在尝试使用 'then()' 但无法完全弄清楚。 “inside promise 2”在 'then()' 1 块中的循环之前被安慰
这是我在代码中所做的:
exports.followers_temp = function(req, res)
{
db.sequelize.query('SELECT DISTINCT public."Users".id as user_id, public."Users".full_name, public."Users".profile_image_url, (SELECT COUNT(*) FROM public."Followships" WHERE public."Followships".leader_id = public."Users".id AND public."Followships".follower_id = :leader_id) AS is_followed FROM public."Users" INNER JOIN public."Followships" ON public."Users".id = public."Followships".follower_id WHERE public."Followships".leader_id = :leader_id LIMIT :limit OFFSET :offset', { replacements: { leader_id: req.params.leader_id, limit: req.params.limit, offset: req.params.offset }, type: db.sequelize.QueryTypes.SELECT}).
then(function(data){
console.log('i am here; length: ' + data.length);
return new Promise(function(resolve, reject) {
console.log('inside promise 1, should have access to data object');
console.log('before loop');
for(let i=0; i < data.length; i++){
var temp = db.sequelize.query('(SELECT COUNT(*) AS is_following FROM public."Followships" WHERE public."Followships".leader_id = ' + data[i].user_id + ' AND public."Followships".follower_id = :my_id)', { replacements: { leader_id: req.params.leader_id, my_id: req.params.my_id, limit: req.params.limit, offset: req.params.offset }, type: db.sequelize.QueryTypes.SELECT})
temp.then(function(value){
// Issue ONE
console.log('type: '+ typeof value); // it's an object
console.log('is_following: '+ value.is_following); // yet it's giving undefined
console.log('value: '+ JSON.stringify(value)); // but it prints out when I stringify it
data[i].is_followed = value.is_following;
});
}
resolve(data);
});
})
.then(function(my_array){
// Issue TWO
console.log('inside promise 2');
return res.status(200).send({
error:false,
message: my_array
});
})
.catch(function(err) {
console.log('inside promise catch');
return res.status(400).send({
error:true,
message: errorHandler.getErrorMessage(err)
});
});
};
这是控制台输出:
i am here; length: 5
inside promise 1, should have
before loop
inside promise 2
type: object
is_following: undefined
value: [{"is_following":"1"}]
type: object
is_following: undefined
value: [{"is_following":"0"}]
type: object
is_following: undefined
value: [{"is_following":"1"}]
type: object
is_following: undefined
value: [{"is_following":"1"}]
type: object
is_following: undefined
value: [{"is_following":"0"}]
请告诉我 -我究竟做错了什么? - 如果你能明智地使用 Promise 语法......那就太好了
感谢您的期待;请忽略菜鸟的错误,因为我现在是菜鸟。
【问题讨论】:
-
循环和承诺不能很好地混合。而是使用
Promise.all -
hmm... Promise.all --- 这对我来说是一个新术语... 我会研究它的功能并在我理解它的情况下尝试使用它。谢谢你的提示。
标签: javascript node.js express npm sequelize.js