Created
December 31, 2019 22:07
-
-
Save prof3ssorSt3v3/3a197be7b52d2a4c828bfd4504460eeb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let myObj = { | |
//add an asyncIterator method to my object | |
[Symbol.asyncIterator]() { | |
//which will return an object that contains a method called next() | |
return { | |
i: 0 /* my counter property */, | |
next() { | |
if (this.i < 3) { | |
//return value from the next method must be an object | |
//the object should contain a value and a done property | |
return new Promise(resolve => { | |
let obj = { value: this.i, done: false }; | |
this.i = this.i + 1; | |
setTimeout(resolve, 1000, obj); | |
//this timeout delay value is not set until next() is called by for await...of | |
}); | |
} | |
//once our counter value is 3 or more tell whoever called next that we are done | |
return new Promise(resolve => { | |
setTimeout(resolve, 3000, { done: true }); | |
}); | |
} | |
}; | |
} | |
}; | |
(async function() { | |
for await (let num of myObj) { | |
console.log(num); | |
} | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* for await(let val of obj) { | |
* use the asynchronous result | |
* } | |
*/ | |
let thing = [ | |
new Promise(resolve => { | |
setTimeout(resolve, 4000, "one"); | |
}), | |
new Promise(resolve => { | |
setTimeout(resolve, 1000, "two"); | |
}), | |
new Promise(resolve => { | |
setTimeout(resolve, 1000, "three"); | |
}) | |
]; | |
//all 3 promises are being created as soon as the page runs | |
//so we need different timeout delay values | |
(async function() { | |
for await (let res of thing) { | |
console.log(res); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment