Home Asynchronous request inside callback of for loop (facebook messenger bot)
Reply: 1

Asynchronous request inside callback of for loop (facebook messenger bot)

stuv Published in 2018-01-11 14:40:59Z

I'm trying to send automated news messages to my subscribed users (+-8000), for this I am using a for loop to pass through each users. the problem is that i am using a asynchronous function inside the callback of an asynchronous function inside my for loop but my bot send all the text then all the generics so it can take up to 8 min for an users beetween he received the text and the generic.

here is my code :

for (user of userList) {
      id: user.id,
      text: Sometext

    (err, data) => {
      if (err) {
        console.err("text => " + err)
      console.log(`Text send ${user}`)


          id: user.id,
          elements: elements
        (err, data) => {
          if (err) {
            console.err("Generic => " + err)
          console.log(`carousel  send ${user}`);

and then in my logs I get

Text send user1
Text send user2
Text send user4
Text send user5
Text send user3

carousel send user1
carousel send user4
carousel send user2
carousel send user5
carousel send user3
mario vasilev
mario vasilev Reply to 2018-01-11 23:17:59Z

So, sendText and sendGeneric are asynchronous functions? Because you never wait them.

Also if you're supporting the latest ecmascript, you can wrap the function your for loop is in with async, and then await every sendText

var someFunc = async function() {
     //Some code ...
     for(user of userList){
         await sendText(/*your function*/);

If you don't support the latest ecmascript for async/await, then you can chain .then for each iteration (something like queue)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317173 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO