I kind of understand the differences between callbacks, promises and async await, but I'm not quite sure how to apply this to my problem.
I stripped away a lot of the code, but basically I have an app running with an endpoint that needs to execute 3 functions (maybe I need a 4th?) and also send a "res.end()" within 3 seconds. The 3 functions are dependent on each other. Do I need to chain these functions? My main() seems completely wrong.
- deleteRule() has to run and finish first
- createRule() must run after deleteRule() has completed
- orderRule() must run after createRule() has completed
router.post('/', function (req, res) {
async function deleteRule() {
axios.delete(DeleteURL, {auth: auth, httpsAgent: agent})
.then(response => {
let deleteRes = response.data
console.log(deleteRes)
})
}
const list = './jsons/list.json'
async function createRule() {
fs.readFile(list, 'utf-8', function(err, data) {
if (err) throw err
var thestuff = JSON.parse(data)
axios.post(CreateURL, thestuff, {auth: auth, httpsAgent: agent})
.then(response => {
let createRes = response.data
console.log(createRes)
})
})
}
async function orderRule() {
axios.put(usOrderURL, theOrder, {auth: auth, httpsAgent: agent})
.then(response => {
let orderRes = response.data
console.log(orderRes)
})
}
async function main() {
const deleteListResult = await deleteRule();
const createListResult = await createRule();
const orderListResult = await orderRule();
}
main();
// res.end must finish in 3 seconds from the initial post on the first line
res.end()
})