Skip to content

Instantly share code, notes, and snippets.

@alastairparagas
Last active August 2, 2018 14:29
Show Gist options
  • Select an option

  • Save alastairparagas/bf24e4e71bf7ad4d0880ffc59ab2e18f to your computer and use it in GitHub Desktop.

Select an option

Save alastairparagas/bf24e4e71bf7ad4d0880ffc59ab2e18f to your computer and use it in GitHub Desktop.
Async I/O in Javascript
const https = require("https");
const urlList = [
"https://reqres.in/api/users?page=1",
"https://reqres.in/api/users?page=2",
"https://reqres.in/api/users?page=3"
];
function getSiteContents(url) {
return new Promise(function (resolve, reject) {
https.get(url, function (res) {
var bodyData = "";
res.on("data", function (chunk) {
bodyData += chunk;
});
res.on("end", function () {
resolve(bodyData);
});
res.on("error", function (error) {
reject(error.message);
});
});
});
}
// One way we can proceed with execution
// Make one Promise out of a list of Promises
Promise.all(urlList.map(getSiteContents))
.then(function (siteContents) {
console.log("Promise based execution --->");
console.log(siteContents);
});
// Another way we can proceed with execution
// "async" is an ES7 feature that makes our Promise/async I/O code look
// more synchronous
async function main () {
const siteContents = await Promise.all(urlList.map(getSiteContents))
console.log("Main() based execution --->");
console.log(siteContents);
}
main();
// As Promises will happen in some future time, this will happen first
console.log("This console.log will most likely happen first");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment