Last active
June 24, 2018 11:01
-
-
Save mevanabey/f77c42f231cf9e8f76acdea97843652e to your computer and use it in GitHub Desktop.
using async/await with map
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
//this code is a sample of a part of a function I wrote to update the courier status of an order every hour. Changed for better understanding | |
orders = [ | |
{ | |
id: 0123, | |
tracking_no: '1234567A', | |
courier_status: '', | |
}, | |
{ | |
id: 0124, | |
tracking_no: '1234567B', | |
courier_status: '', | |
}, | |
{ | |
id: 0125, | |
tracking_no: '1234567C', | |
courier_status: '', | |
} | |
]; | |
//this orderItems constant will be an array of promises which will be pending until all the bellow promises are resolved. | |
const orderItems = orders.map(async order => { | |
const reqUrl = `APIURL/${order.tracking_no}`; | |
try { | |
const status = await axios.get(reqUrl, requestOptions); | |
const status_name = await status.data.tracking_information.status_name; | |
order.courier_status = status_name; | |
return order; | |
} catch(error) { | |
console.log(error); | |
} | |
}); | |
const updatedOrders = await Promise.all(orderItems); | |
//this line below will run only after all the promises in the map has been resolved due to the line above | |
orders = updatedOrders; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment