Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
¿Cómo interceptar un error en una promesa con async/await?

En un proyecto de NodeJs, llamo a mi función asíncrona de esta manera:

 const response = await myFunction();

Aquí está la definición de la función:

 myFunction = async () => { return await new Promise((next, fail) => { // ... axios({ method: 'get', url: apiEndpoint, data: payload }).then(function (response) { // ... next(orderId); }).catch(function (error) { fail(error); }); }); }

¿Cómo debo interceptar correctamente un error si eso sucede? es decir, ¿cómo lo manejo cuando espero la función?

EDITAR: según lo solicitado, un fragmento más completo:

 import express from 'express'; import { helpers } from '../helpers.js'; const router = express.Router(); router.post('/createOrder', helpers.restAuthorize, async (req, res) => { // ... const orderId = await api.createOrder(); let order = { buyOrderId: orderId } const placed = await api.checkPlaced(orderId); if (placed) { let ack = await api.putAck(orderId); order.checksum = placed.checksum; order.ack = ack; } InternalOrder.create(order, (error, data) => { if (error) { return res.status(500).send({ message: error }); } else { res.json("ok"); } }) }) export { router as exchangeRouter }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puede lograrlo y simplificarlo con un bloque try-catch , dependiendo de cómo quiera manejar el error

 async function myFunction () { try { const response = await axios({ method: 'get', url: apiEndpoint, data: payload }) // ... do something with response } catch (error) { // ... do something with error } }

Pero si desea encadenar promesas en su función, puede devolver directamente la llamada axios

 function myFunction () { return axios({ method: 'get', url: apiEndpoint, data: payload }) } // ... myFunction().catch(e => { // ... do something with the error })
about 4 years ago · Juan Pablo Isaza Report

0

Usa probar/atrapar:

 let response; try { response = await myFunction(); } catch (error) { // Handle error here. }
about 4 years ago · Juan Pablo Isaza Report

0

Tu puedes hacer

 try { const response = await axios({ method: 'get', url: apiEndpoint, data: payload }) next(orderId); } catch (error) { fail(error) }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!