https://github.com/klimashkin/racing-for-await-of
Asynchronous iteration over array by promise resolve time
https://github.com/klimashkin/racing-for-await-of
async await for-await-of iteration iterator javascript
Last synced: 3 months ago
JSON representation
Asynchronous iteration over array by promise resolve time
- Host: GitHub
- URL: https://github.com/klimashkin/racing-for-await-of
- Owner: klimashkin
- License: mit
- Created: 2017-12-04T06:11:39.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2017-12-04T07:08:54.000Z (over 7 years ago)
- Last Synced: 2025-02-09T11:18:50.610Z (4 months ago)
- Topics: async, await, for-await-of, iteration, iterator, javascript
- Language: JavaScript
- Size: 2.93 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# racing-for-await-of
Yield value from any resolved promise in array in for-await-of loop as soon as it resolved.If you use for-await-of array of promises, you iterate over it by initial order, doesn't matter if the next promise in given array is resolved before the previous one:
```javascript
const sleep = time => new Promise(resolve => setTimeout(resolve, time));(async function () {
const arr = [
sleep(2000).then(() => 'a'),
'x',
sleep(1000).then(() => 'b'),
'y',
sleep(3000).then(() => 'c'),
'z',
];for await (const item of arr) {
console.log(item);
}
}());// Output
// a
// x
// b
// y
// z
```But sometimes you need to get next result of any promise in given array as soon as it resolved. To achieve it, import current module and wrap your array in for-await-of as shown below:
```javascript
import raceIterator from 'racing-for-await-of';const sleep = time => new Promise(resolve => setTimeout(resolve, time));
(async function () {
const arr = [
sleep(2000).then(() => 'a'),
'x',
sleep(1000).then(() => 'b'),
'y',
sleep(3000).then(() => 'c'),
'z',
];for await (const item of raceIterator(arr)) {
console.log(item);
}
}());// Output
// x
// y
// z
// b
// a
// c
```