Last active
May 24, 2020 19:18
-
-
Save Goloburda/8bedb39aa795b80c1eaa24b611a5df4c to your computer and use it in GitHub Desktop.
for await ()
This file contains 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
function makeRequest(arg) { | |
return new Promise(res => { | |
setTimeout(() => res(arg), 2000); | |
}); | |
} | |
const person = { | |
name() { | |
return makeRequest("Mikita"); | |
}, | |
age() { | |
return makeRequest(25); | |
}, | |
city() { | |
return makeRequest("Hrodna"); | |
} | |
}; | |
person[Symbol.iterator] = function() { | |
let index = -1; | |
const propsArr = Object.getOwnPropertyNames(this); | |
return { | |
async next() { | |
index++; | |
if (propsArr[index]) { | |
const answer = await person[propsArr[index]](); | |
return { done: false, value: answer }; | |
} else { | |
return { done: true, value: null }; | |
} | |
} | |
}; | |
}; | |
(async function() { | |
for await (const item of person) { | |
console.log(item); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment