Await loop over an object
I always rely on bluebird each / all to loop over an array. Until someday I meet the case where I need to use await loop over an object. Surprisingly, after trying on chrome inspector, for loop on object is very doable :
const delayed = (v) => {
return new Promise((res) => {
setTimeout(() => {
res(v)
}, 1000)
})
}
const test = async () => {
const k = { a: 'Happy', b: 'New', c: 'Year!' }
for (let i in k) {
let text = await delayed(k[i])
console.log(text)
}
console.log('DONE!')
}
test ()
Above codes will print a text on variable k with delay every 1 second.
Leave a Reply