1
所以我想获得一个循环数组和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 });
我首先需要让我的所有设备从我的MongoDB集合匹配的用户ID的ID。 SO userIDs是与该集合中的设备绑定的一组ID。一旦我得到设备,我需要从返回的对象中获取设备标记。
因此: 1)调用getDevices传递用户ID数组 2)调用searchRegisterDevices与设备ID。 3)searchRegisterDevices返回设备数组。 4)从该数组中获取设备标记并推送到userDevices数组。 5)回userDevices阵列 6)调用sendNotification时与userDevices
我知道我的问题的阵列,我只是我有一个很难解决这些问题
起初我会抱怨说这不起作用。然后它打我。这工作完美。我不敢相信我没有想到这一点。不是搜索每个设备,而是返回每个ID的每个设备的数组。完善。给予好评! –
@AustinHunter我很高兴它为你提供帮助。 :) – Sachin