Home > Net >  wait 3 seconds, then do next task. inside map
wait 3 seconds, then do next task. inside map

Time:11-26

i have a list of usernames, which are basically accounts

let users = [
"user1","user2","user3","user4","user5","user6","user7"
]
users.map(async (user, i) => {
   console.log(user, i)
   let res = await sendmessage(user)
   if(res) {
     console.log("Message Sent to: "   user)
   }
})

What should happen, is it wait 3 seconds, then send message, then wait 3 seconds, then send message, but what actually is happening. => console.log(user, i) it executes this all at once, I don't understand what is wrong with my code?

CodePudding user response:

Map doesn't give any garantee on sequential execution because every "iteration" have no clue when previous should end.

The easiest way to reach what you expected is to change map to for of.
So your code would looks like this:

let users = [
"user1","user2","user3","user4","user5","user6","user7"
]
for (const user of users){
   console.log(user)
   let res = await sendmessage(user)
   if(res) {
     console.log("Message Sent to: "   user)
   }
}

CodePudding user response:

You can use an asynchronous for loop with a wait function.

const wait = async (ms) => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  })
}

const users = [
  "user1","user2","user3","user4","user5","user6","user7"
];


for(let i = 0; i < users.length; i  ){
  const user = users[i];
  let res = await sendmessage(user)
  if(res) {
    console.log("Message Sent to: "   user)
  }
  await wait(3000);
}

CodePudding user response:

Async await concept and callback functions does not quite go together

since you don't return any data use an ordinary loop and your promises work as you intend them to work.

for(let i = 0; i < users.length; i  ){
    let user = users[i];
    let res = await sendmessage(user)
    if(res) {
      console.log("Message Sent to: "   user)
    }
}

CodePudding user response:

Personally for something like this, I would use a queue type of system and not mess with async/await or multiple timeouts.

let users = [
"user1","user2","user3","user4","user5","user6","user7"
]



const sendMessage = (users, message, delay) => {

  const remaining = users.slice();
  
  const send = () => {
    const user = remaining.shift();  
    console.log(message, user);
    
    if (remaining.length) {
      setTimeout(send, delay);
    }
  }
  
  send();
}

sendMessage(users, "hello", 1000);

  • Related