【发布时间】:2016-09-26 16:11:57
【问题描述】:
所以我试图获得一个带有循环的数组,而 nodejs 的异步特性让我很生气。这是我的代码:
getDevices(userIDs, function(result) {
if (result) {
sendNotification(messageUser, messageText, result);
res.send("Success");
} else {
res.send("ERROR");
}
});
});
function getDevices(userIDs, callback) {
var userDevices = [];
var device = [];
for (var i = 0; i < userIDs.length; i++) {
searchRegisterDevices(userIDs[i], function(result) {
if (result) {
for (var j = 0; j < result.length; j++) {
device = {platform: result[j].platform, token: result[j].token};
userDevices.push(device);
}
} else {
console.log("ERROR");
}
});
}
callback(userDevices);
}
function searchRegisterDevices(userID, callback) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('RegisteredDevices');
collection.find({userID: userID}).toArray(function (err, result) {
if (err) {
console.log("Error: " + err);
} else if (result.length) {
callback(result);
} else {
console.log('No document found');
}
db.close();
});
});
我首先需要从我的 mongodb 集合中取出与 userID 中的 ID 匹配的所有设备。 SO userIDs 是一组与集合中的设备相关联的 ID。获得设备后,我需要从返回的对象中获取设备令牌。
所以: 1) 调用 getDevices 传递用户 ID 数组 2) 使用设备 ID 调用 searchRegisterDevices。 3) searchRegisterDevices 返回一个设备数组。 4) 从该数组中获取设备令牌并推送到 userDevices 数组。 5) 返回用户设备数组 6) 使用 userDevices 数组调用 sendNotification
我知道我的问题,我只是很难解决它们
【问题讨论】:
标签: javascript android arrays node.js mongodb