skip to Main Content

I’m trying to make facebook api requests in a for loop using request module in nodejs. But I need to make the loop and request calls synchronous. What am I doing wrong?

    async function sendRequestAsync(sender, messageData) {
        await request({
            url: "https://graph.facebook.com/v2.6/me/messages",
            qs: {access_token: PAGE_ACCESS_TOKEN},
            method: "POST",
            json: {
                recipient: {id: sender},
                message: messageData
            }
        });
     }

     function sendFoods (sender, results) {
         results.forEach(async result => {
             await request.sendRequestasync(sender, {text: result.cat});
             await request.sendRequestasync(sender, result.data);
             console.log(result);
         });
    }

2

Answers


  1. Your sendRequestAsync function should just return the promise directly from the request call rather than awaiting it. Await is really just syntactic sugar for .then ().

    Login or Signup to reply.
  2. In ES8 Async/Await the script waits for resolving a promise before it continues the execution.

    async function test() {
      for (let i = 0; i < 5; i++) {
        let result = await req('http://google.com');
        console.log(result.resp.statusCode, i);
      };
    };
    
    function req(url) {
      return new Promise(function(resolve, reject) {
        request.get(url, function(err, resp, body) {
          if (err) { reject(err); }
          else { resolve({resp: resp, body: body}); }
        })
      })
    };
    

    Try my live example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search