これは情報がたくさんあるトピックですが、まだ解決できません。ループ内でAsyncが約束します
私は、mysqlサーバに接続するNodeJで作業しています。配列を持っています。配列を繰り返し処理する必要があります。データはmysqlサーバに問い合わせる必要がありますクエリの結果が得られるまでforループの待機が必要ですが、私は多くのことを試しましたが、今はbluebirdの各メソッドで試していますが、まだ正しく動作していません。これが私のコードです。
初期関数は、事前に
おかげ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.isMatching'を返す '、Notifications.execute(sql'を返します...)あなたの 'isMatching'関数i非同期ではないかもしれないが、おそらくあなたのコードを単純化することができるかもしれない。 – arvymetal
このコードは非常に間違っている。まず、もっと簡単なアルゴリズムに取り組んで、約束事で作業することを学ぶべきである(最後に同期コールバック約束を使用する...完全に役に立たない) – trincot
nsynjsを使用してコードを同期的に実行することができます。たとえば、https://github.com/amaksr/nsynjs/tree/master/examples/node-mysqlを参照してください。文の実行。 – amaksr