我对 JavasSript 的 async
、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);
}
});
}
我在一个开关案例中调用此函数,例如,
async function send(){
await sendTextMessage(text);
await sendImageMessage(img);
await sendQuickReply(replies)
}
send()
但是,虽然响应最后显示 sendImageMessage()
,因为当我发送 imageUrl
来生成响应时,此函数可能尚未准备好。
最佳答案
请注意,此答案是针对 the original question 编写的而不是 OP 稍后进行的编辑。
<小时/>async
函数是异步的。其他功能不会等待。
因此,您调用 sendTextMessage
,它又调用 callSendAPI
,然后程序的其余部分继续执行。
callSendAPI
异步运行。它调用 request
并等待 request
返回的 Promise 得到解析。解析完成后,callSendAPI
会获取 request
的返回值(好吧,如果您捕获了返回值,就会如此),然后继续下一行(只有不是下一行)。
async
/await
不会使异步代码同步。他们只是让它看起来像在声明为async
的函数内部,它本身就变成了异步。
您可以将三个函数调用放入各自的 async
函数中,确保每个函数都返回一个 Promise,然后使用 await
调用这三个函数中的每一个。
另请参阅How do I return the response from an asynchronous call? .
关于javascript - 异步等待无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50423873/