javascript - 如何在 Node.js 中使用 Promises 对异步调用进行排序?

标签 javascript node.js promise facebook-messenger

我是 Javascript 新手,无法理解如何让我的函数依次运行。我想使用 Promise 来实现这一点。

我正在按照 Facebook Messenger 教程制作聊天机器人。基本上,我想一个接一个地发送消息。

如果我调用以下几行:

sendTextMessage(recipientID, "1");
sendTextMessage(recipientID, "2");
sendTextMessage(recipientID, "3");
sendTextMessage(recipientID, "4");
sendTextMessage(recipientID, "5");

我希望先发送消息“1”。然后是“2”、“3”等等。 (而不是按随机顺序发送,这就是这里的问题。)

<小时/>

以下是相关的辅助函数。

function sendTextMessage(recipientId, messageText) {
  var messageData = {
    recipient: {
      id: recipientId
    },
    message: {
      text: messageText
    }
  };

  callSendAPI(messageData);
}

这里是callSendAPI函数。

function callSendAPI(messageData) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: PAGE_ACCESS_TOKEN },
    method: 'POST',
    json: messageData

  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      var recipientId = body.recipient_id;
      var messageId = body.message_id;

      if (messageId) {
        console.log("Successfully sent message with id %s to recipient %s", 
          messageId, recipientId);
      } else {
      console.log("Successfully called Send API for recipient %s", 
        recipientId);
      }
    } else {
      console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
    }
  });  
}
<小时/>

我已经被困了一段时间了。任何帮助将不胜感激。

我尝试过这个,但没有成功。 =(

sendTextMessage(recipientID, "1")
.then(sendTextMessage(recipientID, "2"))
.then(sendTextMessage(recipientID, "3"));

最佳答案

要实现此功能,请让两个辅助函数返回 Promise。因此,在 callSendAPI 中,您创建并返回一个,而 sendTextMessage 应该只返回从 callSendAPI 获得的相同 promise 。最后,确保将函数传递给 then 调用,而不是执行函数。您可以使用 .bind() 从现有函数创建一个新函数,并指定调用时应传递的参数。

function callSendAPI(messageData) {
    return new Promise(function (resolve, reject) { // ***
        request({
            uri: 'https://graph.facebook.com/v2.6/me/messages',
            qs: { access_token: PAGE_ACCESS_TOKEN },
            method: 'POST',
            json: messageData
        }, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var recipientId = body.recipient_id;
                var messageId = body.message_id;
                if (messageId) {
                    console.log("Successfully sent message with id %s to recipient %s", 
                                messageId, recipientId);
                } else {
                    console.log("Successfully called Send API for recipient %s", 
                                recipientId);
                }
                resolve(body); // ***
            } else {
                console.error("Failed calling Send API", response.statusCode,
                              response.statusMessage, body.error);
                reject(body.error); // ***
            }
        });
    });
}

function sendTextMessage(recipientId, messageText) {
    var messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            text: messageText
        }
    };
    return callSendAPI(messageData); // *** returns promise
}

sendTextMessage(recipientID, "1")
.then(sendTextMessage.bind(null, recipientID, "2")) // *** pass a function reference
.then(sendTextMessage.bind(null, recipientID, "3"))
.catch(function (body) {
     console.log('aborted');
});

关于javascript - 如何在 Node.js 中使用 Promises 对异步调用进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42332999/

相关文章:

javascript - 为什么在 Promise 中调用的函数中没有通过闭包定义解析?

javascript - 我如何使用 Jasmine 测试 AngularJS promise 返回的内容?

javascript - Greasemonkey 脚本自动选择并单击值/选择器中包含非英文字符的特定按钮?

javascript - CodeMirror更改模式没有样式

javascript - 在 Node 中生成后捕获子进程中的输入

javascript - 如何使用 Joi 最新版本验证枚举字符串?

Angular 2等待同步方法

javascript - Highcharts 日期不准确

javascript - 将函数类型分配给对象的方法

node.js - 如何修改node js响应