let promise wait a couple of seconds before return

后端 未结 4 1863
迷失自我
迷失自我 2021-02-19 09:07

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



        
相关标签:
4条回答
  • 2021-02-19 09:16

    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))
    
    0 讨论(0)
  • 2021-02-19 09:29

    The short version:

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

    Example:

    async function myFunc(user) {
      await wait(3000);
    
      sendMessage(user.name);
    }
    
    0 讨论(0)
  • 2021-02-19 09:30

    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));
    
    0 讨论(0)
  • 2021-02-19 09:31

    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)
        });
      }
    )
    
    0 讨论(0)
提交回复
热议问题