Entiendo las diferencias entre las devoluciones de llamada, las promesas y la espera asincrónica, pero no estoy muy seguro de cómo aplicar esto a mi problema.
Eliminé gran parte del código, pero básicamente tengo una aplicación ejecutándose con un punto final que necesita ejecutar 3 funciones (¿quizás necesito una cuarta?) y también enviar un "res.end()" dentro de 3 segundos. Las 3 funciones dependen unas de otras. ¿Necesito encadenar estas funciones? Mi main() parece completamente incorrecto.
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() })Las llamadas a then() devuelven promesas, pero no haces nada con ellas. Debes await o return .
Ya que declaraste tus funciones como async , usa await en ellas; ese es el punto central de la palabra clave async :
async function deleteRule() { let response = await axios.delete(DeleteURL, {auth: auth, httpsAgent: agent}); console.log(response.data); return response.data; }Realice un cambio similar en las otras dos funciones de regla.
import fs from 'fs-extra' const list = './jsons/list.json' async function deleteRule() { const response = await axios.delete(DeleteURL, {auth: auth, httpsAgent: agent}) const deleteRes = response.data console.log(deleteRes) return deleteRes } async function createRule() { const data = await fs.readFile(list, 'utf-8') const theStuff = JSON.parse(data) const response = await axios.post(CreateURL, theStuff, {auth: auth, httpsAgent: agent}) const createRes = response.data console.log(createRes) return createRes } async function orderRule() { const response = await axios.put(usOrderURL, theOrder, {auth: auth, httpsAgent: agent}) const orderRes = response.data console.log(orderRes) return orderRes } router.post('/', async function (req, res) { const deleteListResult = await deleteRule(); const createListResult = await createRule(); const orderListResult = await orderRule(); // res.end must finish in 3 seconds from the initial post on the first line res.end() })