【发布时间】:2017-10-30 05:57:09
【问题描述】:
我知道这是一个有很多信息的话题,但我仍然无法解决这个问题。
我正在使用连接到 mysql 服务器的 NodeJ,我有一个数组,我需要迭代数组并对数据做一些事情,问题是我需要对 mysql 服务器进行查询,但我需要到for循环等到我得到查询结果,我已经尝试了很多东西,现在我正在尝试使用bluebird的.each方法但仍然无法正常工作,这是我的代码。
初始函数是 Notification.getByUser
提前致谢
'use strict';
var Promise = require("bluebird");
module.exports = function(Notifications) {
Notifications.execute = function(sql, itemId) {
return new Promise((resolve, reject) => {
this.dataSource.connector.execute(sql, (e, result) => {
console.log('-----RESULT----', itemId);
console.log(result);
console.log('-----ERROR-----', itemId);
console.log(e);
if (result.length === 0) {
resolve(false);
} else {
resolve(true);
}
});
});
};
Notifications.isMatching = function(item, user, type) {
return new Promise((resolve, reject) => {
console.log(type, item, user);
if (item !== null) {
if (item !== user) {
resolve(false);
}
}
resolve(true);
});
};
Notifications.getByUser = function(userId, isZolver, countryId, cityId, userState, cb) {
var where = { status: 1 };
var plainText = '';
var items = Notifications.find({ where });
Promise.each(items, item => {
return Notifications.isMatching(item.isZolver, isZolver, 'isZolver')
.then(() => {
Notifications.isMatching(item.cityId, cityId, 'cityId');
})
.then(() => {
if(item.extraCondition !== null && item.extraCondition !== '') {
var sql = item.extraCondition.replace(/:user_id/g, userId);
// console.log(sql);
Notifications.execute(sql, item.id)
.then(render => console.log('extraCondition', render));
} else {
console.log('extraCondition', true);
}
});
}).then(res => {
// console.log('res del loop', res);
});
cb(null, 'ok');
};
};
【问题讨论】:
-
您的
.then调用必须返回一些内容(return Notifications.execute(sql、return Notifications.isMatching...)。而且你的isMatching函数不是异步的,也许你可以简化你的代码 -
这段代码有很多错误:您可能应该首先解决一个更简单的算法,学习使用 Promise(而不是将它们与最后的同步回调混合,这只是使用承诺......完全没用)
-
你可以通过nsynjs同步运行你的代码,顺序语句执行的例子请看github.com/amaksr/nsynjs/tree/master/examples/node-mysql。
标签: javascript node.js promise bluebird