Skip to content

Commit 51a76ef

Browse files
authored
Add Promise.race for completeness
Promise.all and Promise.race are usually considered a pair, thus I added Promise.race for completeness.
1 parent 5ec8155 commit 51a76ef

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

docs/promise.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,5 +438,20 @@ Promise.all([loadItem(1),loadItem(2)])
438438
}); // overall time will be around 1s
439439
```
440440

441+
Sometimes, you want to run a series of async tasks, but you get all you need as long as any one of these tasks is settled. `Promise` provides a static `Promise.race` function for this scenario:
442+
443+
```ts
444+
var task1 = new Promise(function(resolve, reject) {
445+
setTimeout(resolve, 1000, 'one');
446+
});
447+
var task2 = new Promise(function(resolve, reject) {
448+
setTimeout(resolve, 2000, 'two');
449+
});
450+
451+
Promise.race([task1, task2]).then(function(value) {
452+
console.log(value); // "one"
453+
// Both resolve, but p2 is faster
454+
});
455+
```
441456

442457
[polyfill]:https://github.com/stefanpenner/es6-promise

0 commit comments

Comments
 (0)