let promise wait a couple of seconds before return

荒凉一梦 提交于 2020-12-29 09:34:05

问题


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?


回答1:


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))



回答2:


The short version:

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

Example:

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

  sendMessage(user.name);
}



回答3:


A different approach - useful if you want to do this sort of thing in many places

This bit is done once

Promise.prototype.thenWait = function thenWait(time) {
    return this.then(result => new Promise(resolve => setTimeout(resolve, time, result)));
};

Then you can use it, like this usage for your example, anywhere

apiGetLoggedInUser.thenWait(3000).then(user => sendMessage(user.name));



回答4:


Create new promise which will call sendMessage after a timeout.

apiGetLoggedInUser.then(
  user => {
    return new Promise((resolve, reject) => {
       setTimeout(() => {
          sendMessage(user.name).then(resolve, reject);
       }, 3000)
    });
  }
)


来源:https://stackoverflow.com/questions/42529476/let-promise-wait-a-couple-of-seconds-before-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!