Add delay to javascript method that returns promise

后端 未结 2 561
醉酒成梦
醉酒成梦 2020-12-10 05:07

I\'m currently trying to learn Angular 2, typescript, promises, etc. I\'ve setup a small app for developer tools and a service that just returns hard-coded data. This is to

相关标签:
2条回答
  • 2020-12-10 05:49

    Delayed native promise

    New promise that resolves with undefined

    return new Promise(resolve =>
      setTimeout(resolve, 5000)
    );
    

    New promise that resolves with a value

    return new Promise(resolve => 
      setTimeout(() => resolve(value), 5000)
    );
    

    Existing promise

    return promise.then(value => 
      new Promise(resolve => 
        setTimeout(() => resolve(value), 5000)
      )
    );
    

    Delayed Bluebird promise

    Bluebird promise library has better performance and convenient features that can be used out of the box to delay promise chains.

    New promise that resolves with undefined

    return Bluebird.delay(5000);
    

    New promise that resolves with a value

    return Bluebird.resolve(value).delay(5000);
    // or
    return Bluebird.delay(5000).return(value);
    

    Existing promise

    return bluebirdPromise.delay(5000);
    

    Delayed promise with RxJS

    RxJS is already used in Angular 2/4 projects and can be used to create or transform promises with RxJS operators and small overhead.

    New promise that resolves with undefined

    return Observable.of().delay(5000).toPromise();
    // or
    return Observable.interval(5000).first().toPromise();
    

    New promise that resolves with a value

    return Observable.of(value).delay(5000).toPromise();
    

    Existing promise

    return Observable.fromPromise(promise).delay(5000).toPromise();
    
    0 讨论(0)
  • 2020-12-10 05:49

    Delayed result with RxJS 6

    You can use the following code to delay values in RxJs 6 by n ms.

    With no specific value (will emit 0)

    return timer(n);
    

    With a set value

    return of(value).pipe(delay(n));
    

    or

    return timer(n).pipe(mapTo(value));
    

    from a promise

    return from(promise).pipe(delay(n));
    

    to return a promise

    put .toPromise() on any of the previous examples after the pipe.

    return timer(n).toPromise();
    
    return of(value).pipe(delay(n)).toPromise();
    

    etc.

    0 讨论(0)
提交回复
热议问题