2017-09-25 99 views
1

我正在使用javascript来使用facebook发送api。在javascript中运行一个接一个的函数

function sendmessage(callback) { 
    for (i = 0; i < recipientId.length; i++) { 
     var messageData = { 
     recipient: { 
      id: recipientId[i] 
     }, 
     message: { 
      text: messageText 
     } 
     }; 
     callSendAPI(messageData, pagetoken, id_notsent); 
    } 
    return callback(); 
    } 

    function sendstatus() { 
    if (id_notsent.length == 0) { 
     res.statusCode = 200; 
     res.message = "Successfully sent generic message to all recipients"; 
    } else { 
     res.statusCode = 400; 
     res.message = "Unable to send message to all users. Message not sent to recipients : " + id_notsent.toString(); 
    }; 
    resp.send(res); 
    } 
    sendmessage(sendstatus); 

什么,我要做的是更新SendMessage函数将基本上包含用户ID correspoding到消息无法发送,然后相应地发回的响应使用sendstatus函数内部的id_notsent变量。但问题在于sendSessage中的回调在callSendAPI函数完成之前被调用。

回答

1

我怀疑callSendAPI返回某种Promise(或有一个回调,你可以变成一个承诺)。

的结构,那么你的sendMessage()功能应该是围绕

const promises = recipentId.map(id => { 
    ... 
    return callSendAPI(messageData, pagetoken, id_notsent); 
}); 
Promise.all(promises).then(callback); 

基本上线:获得适用于所有电话的承诺,恨不得用Promise.all完成,然后回调

+0

其实我没有发送任何从callSendAPI函数返回。那么如何在这种情况下进一步采用这种解决方案呢? –

+0

'callSendAPI'必须返回一个Promise或者提供一个回调参数。如果不这样做,则无法知道何时完成对服务器的异步调用 –

1

您有多个soluce这里:


使用async/await ES8模式。

function async sendmessage() { 
    for (i = 0; i < recipientId.length; i++) { 
     var messageData = { ... }; 

     await callSendAPI(messageData, pagetoken, id_notsent); 
    } 

    return ...; 
    } 

创建一个递归函数那会打电话一一callSendAPI

例如

function sendmessage({ 
    recipientId, 
    callback, 
    i = 0, 
    rets = [], 
}) { 
    // our work is done 
    if (i >= recipientId.length) return callback(rets); 

    const messageData = { ... }; 

    // Perform one request 
    callSendAPI(messageData, pagetoken, id_notsent, (ret) => { 

     // Call next 
     return sendmessage({ 
     recipientId, 
     callback, 
     rets: [ 
      ...rets, 
      ret, 
     ], 
     i: i + 1, 
     }); 
    }); 
    } 

您可以使用callback(你现在在做什么),或任一Promise

相关问题