Skip to content

Instantly share code, notes, and snippets.

@stevemu
Created December 9, 2018 00:41
Show Gist options
  • Save stevemu/80c8bbcc7dc7497cd53bfd5faab0cb92 to your computer and use it in GitHub Desktop.
Save stevemu/80c8bbcc7dc7497cd53bfd5faab0cb92 to your computer and use it in GitHub Desktop.
run mutiple promises in one async function
const fetch = require('node-fetch'); // fetch polyfill in node.js; not required in front end situation
// returns an promise, so it can be used by await
async function getTodo(id) {
return new Promise((resolve, reject) => {
fetch('https://jsonplaceholder.typicode.com/todos/' + id)
.then(response => response.json())
.then(json => {
// success
// return data through resolve
resolve(json);
})
.catch(() => {
// error
// caller can catch the error in try .. catch .. block
reject();
})
});
}
// call this function as a promise, or use await in another async function
async function getTodos(ids) {
let todos = [];
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
let todoObj = await getTodo(id);
todos.push(todoObj);
}
return todos;
}
// use getTodos in another async function
// such as inside your express route handler
async function run() {
const todoIds = ["1", "2", "3"];
let todos = await getTodos(todoIds);
return todos;
}
// test
run().then((todos) => {
console.log(todos);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment