Delay chained promise

后端 未结 3 1039
我在风中等你
我在风中等你 2020-12-07 05:53

I\'m trying to do the following but it isn\'t working. How can I adjust the code to have a delay between .then and .done?

myServi         


        
相关标签:
3条回答
  • 2020-12-07 06:12

    You can create a simple delay function that returns a promise and use that in your promise chain:

    function delay(t, val) {
       return new Promise(function(resolve) {
           setTimeout(function() {
               resolve(val);
           }, t);
       });
    }
    
    myService.new(a).then(function(temp) {
        return delay(60000, temp);
    }).then(function(temp) {
        return myService.get(a, temp);
    }).then(function (b) {
        console.log(b);
    });
    

    You could also augment the Promise prototype with a .delay() method (which some promise libraries like Bluebird already have built-in). Note, this version of delay passes on the value that it is given to the next link in the chain:

    Promise.prototype.delay = function(t) {
        return this.then(function(val) {
            return delay(t, val);
        });
    }
    

    Then, you could just do this:

    myService.new(a).delay(60000).then(function(temp) {
        return myService.get(a, temp);
    }).then(function (b) {
        console.log(b);
    });
    
    0 讨论(0)
  • 2020-12-07 06:25

    You can create a .delay() function set at Promise.prototype which returns a new Promise having value of original promise.

    Promise.prototype.delay = function(t) {
      return this.then(function(data) {
        return new Promise(function(resolve) {
          setTimeout(resolve, t || 0, data);
        })
      })
    };
    
    Promise.resolve(123)
    .delay(6000)
    .then(function(data) {
      console.log(data)
    });

    0 讨论(0)
  • 2020-12-07 06:38

    A slightly improved version of jfriend00's approach avoids needing the pass the resolved value like this:

    function delay(t) {
      return (val) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => resolve(val), t)
        })
      }
    }
    

    can be used like this:

    myService.new(a)
      .then(delay(60000))
      .then(function(temp) {
        return myService.get(a, temp);
      }).then(function (b) {
        console.log(b);
      });
    
    0 讨论(0)
提交回复
热议问题