Created
December 9, 2018 00:41
-
-
Save stevemu/80c8bbcc7dc7497cd53bfd5faab0cb92 to your computer and use it in GitHub Desktop.
run mutiple promises in one async function
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 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