async await not working properly
Solution 1
Note this answer was written against the original question and not later edits made by the OP.
An async
function is asynchronous. Other functions will not wait for it.
So you call sendTextMessage
which calls callSendAPI
and then the rest of the program carries on.
callSendAPI
runs asynchronously. It calls request
and waits for the promise returned by request
to be resolved. When it has resolved, callSendAPI
picks up the return value of request
(well, it would if you captured the return value) and then continues with the next line (only there isn't a next line).
async
/ await
do not make asynchronous code synchronous. They just make it look like it in inside the function declared as async
which, itself, becomes asynchronous.
You could put your three function calls in an async
function of their own, make sure each one returns a Promise, and then call each of those three with await
.
See also How do I return the response from an asynchronous call?.
Solution 2
I hope that all you want todo is process some operations in strict order.
This is why async and await in ES6 exists.
So by example it may be like this do A then do B then do C or A > B > C
As you can see the last method do3 has only 500 ms delay but it is executed as last and not as first one. Without async and await operators it would be executed as first function and this is default behavior of JavaScript execution. Broser will execute sync code as first and async after. But not with async and await anymore :)
You should also know that if you prefix string, number of function with await then the will be transformed into promise automatically.
The console will print :
'juraj1'
'juraj2'
'juraj3'
here is simple example :
function do1() {
return new Promise(resolve => {
return setTimeout(() => resolve("juraj1"), 3000);
});
}
function do2() {
return new Promise(resolve => {
return setTimeout(() => resolve("juraj2"), 2000);
});
}
function do3() {
return new Promise(resolve => {
return setTimeout(() => resolve("juraj3"), 500);
});
}
async function ForceAsynTOBeSync() {
const a = await do1();
console.log(a);
const b = await do2();
console.log(b);
const c = await do3();
console.log(c);
}
ForceAsynTOBeSync();
Related videos on Youtube
Nikhil Savaliya
I believe: Challenges are mortal. Legacy is immortal. Twilio champion 👑🏆 Javascript Artist 👨🏻🎤
Updated on June 04, 2022Comments
-
Nikhil Savaliya almost 2 years
I am new to JavasSript's
async
,await
andpromise
features.What I am doing is,
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); } }); }
I am calling this functions in one switch case like,
async function send(){ await sendTextMessage(text); await sendImageMessage(img); await sendQuickReply(replies) } send()
But while response shows
sendImageMessage()
last because this function may be not getting ready when I am sendingimageUrl
to generate a response.-
Praveen Soni almost 6 yearscan you share a jsfiddle of your problem, it helps
-
Nishant almost 6 yearsIf you are new, learn about asynchronous programming concepts like
callbacks
,promises
,async
,await
in that order. Otherwise, you might end up confused. -
Praveen Soni almost 6 yearswhat is that request function call in
callSendAPI
function, can you describe it. -
Nikhil Savaliya almost 6 years@PraveenSoni Request function will generate the payload based on the data it get from the three functions and will send it to specific facebook account.
-
Nikhil Savaliya almost 6 years@PraveenSoni in facebook messenger i am getting image at last while i want image in between other two response
-
Praveen Soni almost 6 yearsis
request
fn is made by you, or some library functionality ? can you post that too -
Nikhil Savaliya almost 6 years@PraveenSoni its just formatted function made by me. but the actual reason is the image response is generated at last
-
Praveen Soni almost 6 yearsdidn't get you. is issue is due to that request function ?
-
Nikhil Savaliya almost 6 yearsLet us continue this discussion in chat.
-
-
Nikhil Savaliya almost 6 yearsi already tried this but still not working look at the edited code
-
Jonas Wilms almost 6 years@nikhil
await sendTextMessage(text); await sendImageMessage(imgUrl); await sendQuickReply(replies)
-
Praveen Soni almost 6 yearsto await callSendAPI, it should return a promise
-
Jonas Wilms almost 6 years@praveen it does. :/
-
Praveen Soni almost 6 yearsI can't see any return there
-
Nikhil Savaliya almost 6 yearsi changed while calling function but no luck, a function that sends image it still sending last response
-
Praveen Soni almost 6 years@JonasW.
await sendTextMessage(text); await sendImageMessage(imgUrl); await sendQuickReply(replies)
only valid, when second one need to execute after first one -
Quentin almost 6 years@Sven - The OP has significantly altered their code since I answered the question.
-
Svenskunganka almost 6 yearsAh that explains it, my bad!
-
Nikhil Savaliya almost 6 yearsthe problem is in request