2017-05-30 64 views
0

我很難循環下面的負載清單,併爲我的朋友列表調用具有不同值的Parse.push.send方法。我相信我應該使用承諾,但我不知道如何去做。任何幫助將不勝感激。解析推送發送方法問題

Parse.Cloud.define('senderChannel', function(request, response) { 
    /* getting parameters */ 
    var params = request.params; 
    var senderId = params.senderId; 
    var sharedValue = params.sharedValueList; 
    var recipientList = params.recipientList; 
    var friendCount = params.friendCount; 

    var pushQuery = new Parse.Query(Parse.Installation); 
    pushQuery.equalTo("deviceType", "android"); 

    var payloadList = []; 

    if(friendCount > 1) { 
    /* if friendCount is greater than 1 build custom payload for each friend */ 
    var friendList = recipientList.split(','); 
    var valueList = sharedValue.split(','); 

    var friendListArray = []; 

    for(var item in friendList) { 
     friendListArray.push(item); 
    } 

    for(var value in valueList) { 
     var payload = {"title": senderId, "alert": value}; 
     payloadList.push(payload); 
    } 

    pushQuery.containedIn("device_id", friendListArray); 

    } else { 

     pushQuery.equalTo("device_id", recipientList); 
     var payload = {"title": senderId, "alert": sharedValue}; 
     payloadList.push(payload); 
    } 

    payloadList.forEach(function(payload, index){ 
     /* Send push to every friend */ 
     Parse.Push.send({ 
      where: pushQuery, 
      data: payload, 
     }, { success: function() { 
      console.log("#### PUSH OK"); 
     }, error: function(error) { 
      console.log("#### PUSH ERROR" + error.message); 
     }, useMasterKey: true}); 

     response.success('success'); 
    }); 
}); 

回答

0

我已經能夠通過將推入函數添加到數組中並使用Parse Promise來解決我的問題。下面是代碼

payloadList.forEach(function(payload, index){ 
 

 
     promises.push(sendPush(payload)); 
 

 
    }); 
 

 
    Parse.Promise.when(promises).then(function(){ 
 
     console.log("All pushes have completed !!!"); 
 
    }); 
 

 
    function sendPush(payloadMessage){ 
 

 
     Parse.Push.send({ 
 
      where: pushQuery, 
 
      data: payloadMessage, 
 
     }, { success: function() { 
 
      console.log("#### PUSH OK"); 
 
     }, error: function(error) { 
 
      console.log("#### PUSH ERROR" + error.message); 
 
     }, useMasterKey: true}); 
 

 
     response.success('success'); 
 
    }