私はループで配列を取得しようとしていますが、nodejsの非同期性が私を殺しています。ここに私のコードは次のとおりです。私は非同期を停止できません
\t getDevices(userIDs, function(result) {
\t \t if (result) {
\t \t \t sendNotification(messageUser, messageText, result);
\t \t \t res.send("Success");
\t \t } else {
\t \t \t res.send("ERROR");
\t \t }
\t });
\t
});
function getDevices(userIDs, callback) {
\t var userDevices = [];
\t var device = [];
\t
\t for (var i = 0; i < userIDs.length; i++) {
\t \t \t searchRegisterDevices(userIDs[i], function(result) {
\t \t \t \t if (result) {
\t \t \t \t \t for (var j = 0; j < result.length; j++) {
\t \t \t \t \t \t device = {platform: result[j].platform, token: result[j].token};
\t \t \t \t \t \t userDevices.push(device); \t \t
\t \t \t \t \t }
\t \t \t \t } else {
\t \t \t \t \t console.log("ERROR");
\t \t \t \t }
\t \t \t }); \t
\t }
\t callback(userDevices);
}
function searchRegisterDevices(userID, callback) {
\t MongoClient.connect(url, function(err, db) {
\t \t if (err) {
\t \t \t console.log(err);
\t \t } else {
\t \t \t console.log("We are connected");
\t \t }
\t \t
\t \t var collection = db.collection('RegisteredDevices');
\t \t collection.find({userID: userID}).toArray(function (err, result) {
\t \t \t if (err) {
\t console.log("Error: " + err);
\t } else if (result.length) {
\t \t \t \t callback(result);
\t \t } else {
\t console.log('No document found');
\t }
\t db.close();
\t });
\t });
私は最初のユーザーIDにIDと一致する私のMongoDBのコレクションのうち、私のすべてのデバイスを取得する必要があります。 SO userIDsは、コレクション内のデバイスに関連付けられているIDの配列です。デバイスを取得すると、返されたオブジェクトからデバイストークンを取得する必要があります。
So: 1)ユーザーIDの配列を渡すgetDevicesを呼び出します。 2)デバイスIDを使用してsearchRegisterDevicesを呼び出します。 3)searchRegisterDevicesは、デバイスの配列を返します。 4)その配列からデバイストークンを取り出し、userDevices配列にプッシュします。 5)リターンuserDevices配列 6)userDevices
私は私の問題を知っているの配列とsendNotificationをを呼び出して、私はちょうどあなたがそれらを取得する必要があり、各ユーザのユーザデバイスを彼らに
私はこれがうまくいかないと言って文句を言った。その後、私に当たった。これは完璧です。私はこれを考えなかったとは信じられません。各デバイスを検索する代わりに、すべてのIDのすべてのデバイスの配列を返します。完璧。 Upvote! –
@AustinHunter私はあなたを助けてくれてうれしいです。 :) – Sachin