Created
June 12, 2019 10:09
-
-
Save carlosazaustre/d98fb1580f797b722a6326eb3f2024ed to your computer and use it in GitHub Desktop.
Async API calls inside While Loop (node.js)
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
const requestPromise = require('request-promise-native'); | |
const API = 'https://jsonplaceholder.typicode.com/posts/'; | |
function makeAPICall(id) { | |
return requestPromise({ | |
url: API + id, | |
method: 'GET', | |
json: true | |
}); | |
} | |
async function processUsers() { | |
let id = 1; | |
let result = []; | |
while (id < 10) { | |
let data = await makeAPICall(id); | |
console.log('fetching data from ', id); | |
result.push(data); | |
id += 1; | |
} | |
return result; | |
} | |
async function doIt() { | |
console.log('starting...'); | |
console.time('run') | |
let result = await processUsers(); | |
console.timeEnd('run'); | |
console.log(result); | |
} | |
doIt(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment