async await not working properly

12,399

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();
Share:
12,399

Related videos on Youtube

Nikhil Savaliya
Author by

Nikhil Savaliya

I believe: Challenges are mortal. Legacy is immortal. Twilio champion 👑🏆 Javascript Artist 👨🏻‍🎤

Updated on June 04, 2022

Comments

  • Nikhil Savaliya
    Nikhil Savaliya almost 2 years

    I am new to JavasSript's async, await and promise 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 showssendImageMessage() last because this function may be not getting ready when I am sending imageUrl to generate a response.

    • Praveen Soni
      Praveen Soni almost 6 years
      can you share a jsfiddle of your problem, it helps
    • Nishant
      Nishant almost 6 years
      If you are new, learn about asynchronous programming concepts like callbacks, promises, async, await in that order. Otherwise, you might end up confused.
    • Praveen Soni
      Praveen Soni almost 6 years
      what is that request function call in callSendAPI function, can you describe it.
    • Nikhil Savaliya
      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
      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
      Praveen Soni almost 6 years
      is request fn is made by you, or some library functionality ? can you post that too
    • Nikhil Savaliya
      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
      Praveen Soni almost 6 years
      didn't get you. is issue is due to that request function ?
    • Nikhil Savaliya
      Nikhil Savaliya almost 6 years
  • Nikhil Savaliya
    Nikhil Savaliya almost 6 years
    i already tried this but still not working look at the edited code
  • Jonas Wilms
    Jonas Wilms almost 6 years
    @nikhil await sendTextMessage(text); await sendImageMessage(imgUrl); await sendQuickReply(replies)
  • Praveen Soni
    Praveen Soni almost 6 years
    to await callSendAPI, it should return a promise
  • Jonas Wilms
    Jonas Wilms almost 6 years
    @praveen it does. :/
  • Praveen Soni
    Praveen Soni almost 6 years
    I can't see any return there
  • Nikhil Savaliya
    Nikhil Savaliya almost 6 years
    i changed while calling function but no luck, a function that sends image it still sending last response
  • Praveen Soni
    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
    Quentin almost 6 years
    @Sven - The OP has significantly altered their code since I answered the question.
  • Svenskunganka
    Svenskunganka almost 6 years
    Ah that explains it, my bad!
  • Nikhil Savaliya
    Nikhil Savaliya almost 6 years
    the problem is in request