我知道這是一個有很多信息的話題,但我仍然無法解決這個問題。我有一個數組,我需要迭代數組,並做一些與數據的東西,事情是我需要做一個查詢到MySQL服務器,但我需要for循環等待,直到我得到了查詢的結果,我已經嘗試了很多東西,現在我正在嘗試使用.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'調用必須返回的東西('返回Notifications.execute(sql','返回Notifications.isMatching' ...) 。你的'isMatching'函數不是異步的,也許你可以簡化你的代碼 – arvymetal
這段代碼有太多的錯誤:你應該首先解決一個更簡單的算法,學習使用promise(而不是在最後使用同步回調來混合它們,它只是使用promises ...完全無用) – trincot
您可以通過nsynjs以同步方式運行您的代碼,請參閱https://github.com/amaksr/nsynjs/tree/master/examples/node-mysql,例如順序語句執行。 – amaksr