Nik*_*iya 2 javascript asynchronous node.js promise es6-promise
async我对 JavasSript 的和await功能很陌生promise。
我正在做的是,
async function sendTextMessage(text) {
console.log("----1----");
var messageData = {
message: {
text: text
}
};
await callSendAPI(messageData);
}
async function sendImageMessage(imageUrl) {
console.log("----2----");
var messageData = {
message: {
url: imageUrl
}
};
await callSendAPI(messageData);
}
async function sendQuickReply(replies) {
console.log("----3----");
var messageData = {
message: {
text: text,
quick_replies: replies
}
};
await callSendAPI(messageData);
}
async function callSendAPI(messageData) {
await request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: config.FB_PAGE_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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我在一个开关案例中调用此函数,例如,
async function send(){
await sendTextMessage(text);
await sendImageMessage(img);
await sendQuickReply(replies)
}
send()
Run Code Online (Sandbox Code Playgroud)
但是,虽然响应显示在最后,因为当我发送以生成响应sendImageMessage()时,此功能可能尚未准备好。imageUrl
请注意,这个答案是针对原始问题编写的,而不是 OP 后来进行的编辑。
函数async是异步的。其他功能不会等待它。
所以你调用了sendTextMessagewhich callSendAPI,然后程序的其余部分继续进行。
callSendAPI异步运行。它调用request并等待返回的承诺request得到解决。当它解决后,callSendAPI获取返回值request(好吧,如果您捕获了返回值,就会发生),然后继续下一行(只是没有下一行)。
async/await不要使异步代码同步。他们只是让它看起来像在声明为函数内部的async那样,它本身变得异步。
您可以将三个函数调用放入async各自的函数中,确保每个函数都返回一个 Promise,然后使用await.
另请参阅如何从异步调用返回响应?。
| 归档时间: |
|
| 查看次数: |
13724 次 |
| 最近记录: |