Last active
August 2, 2018 14:29
-
-
Save alastairparagas/bf24e4e71bf7ad4d0880ffc59ab2e18f to your computer and use it in GitHub Desktop.
Async I/O in Javascript
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
| 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