Created
April 12, 2019 10:59
-
-
Save stevemu/d73ed3fb73689aad41417fa5d18a199a to your computer and use it in GitHub Desktop.
demoing using await with a promise 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