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

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

stuv
1#
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) {
  sendText({
      id: user.id,
      text: Sometext
    },
    //////CALLBACK/////////

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

      /////IT SHOULD SEND THE GENERIC EVERYTIME WHEN THE TEXT CALLBACK

      sendGeneric({
          id: user.id,
          elements: elements
        },
        //////CALLBACK/////////
        (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
2#
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