[go: nahoru, domu]

Skip to content

Commit

Permalink
AsyncArray
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-karpenko committed Apr 20, 2019
1 parent 0460497 commit 48a4bdc
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions async-iteration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
async function print(msg, delay) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("delay:" + msg);
resolve(msg);
}, delay);
});
}

async function f() {
for await (let a of [print("1", 3000), print("2", 1000)]) {
console.log("loop:", a);
}
}

// f();

const SyncArray = {
[Symbol.iterator]: function() {
let i = 3;
return {
next: () => {
if (i > 0) {
i--;
return {
value: i
};
} else {
return {
done: true
}
}
}
};
}
};

/**
* Allows sequential iteration over array of promises
*/
class AsyncArray {
constructor(data) {
this.data = data;
}
[Symbol.asyncIterator]() {
let iterator = this.data.values();
return {
next: () => {
let result = iterator.next();
if (result.value) {
return result.value().then(value => {
return {value};
});
}
return {done: true};
}
};
}
}

async function asyncLoop() {
for await (let a of new AsyncArray([print.bind(null, "1", 3000), print.bind(null, "2", 1000)])) {
console.log("loop:", a);
}
}

asyncLoop();

0 comments on commit 48a4bdc

Please sign in to comment.