Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

let promise wait a couple of seconds before return

Tags:

I'm having a function returning a promise. In this function, we call a third party vender to send some push notification through their server.

it looks like

apiGetLoggedInUser.then(
  user => {
    return sendMessage(user.name);
  }
)

However the thing is we decided to wait for 3 seconds before we really call this sendMessage function. However we'd prefer not to change sendMessage since it's provided.

I'm wondering how to really do the "wait" part in this scenario since promise is used to remove "sync" operations.

Am I understanding correctly? What shall I do?

like image 639
Eddie Xie Avatar asked Mar 01 '17 10:03

Eddie Xie


2 Answers

The short version:

function wait(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
}

Example:

async function myFunc(user) {
  await wait(3000);

  sendMessage(user.name);
}
like image 149
DarkNeuron Avatar answered Oct 26 '22 21:10

DarkNeuron


Insert another promise in the chain which delays the next one:

apiGetLoggedInUser
    .then(user => {
        return new Promise(resolve => setTimeout(() => resolve(user), 3000));
    })
    .then(user => sendMessage(user.name))
like image 24
deceze Avatar answered Oct 26 '22 21:10

deceze