Skip to content

Instantly share code, notes, and snippets.

@carlosazaustre
Created June 12, 2019 10:09
Show Gist options
  • Save carlosazaustre/d98fb1580f797b722a6326eb3f2024ed to your computer and use it in GitHub Desktop.
Save carlosazaustre/d98fb1580f797b722a6326eb3f2024ed to your computer and use it in GitHub Desktop.
Async API calls inside While Loop (node.js)
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