0

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);
         });
    }
0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It worked like a charm. Just a quick question, what if I wanted catch resolve and reject separately with await?
You're welcome. Reject will throw an error, if you need it in the result variable, change reject(err) to resolve(err), so the result will be the error message.
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 ().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.