簡體   English   中英

如何使用 async/await 攔截 Promise 上的錯誤?

[英]How to intercept error on a Promise with async/await?

在 NodeJs 項目中,我以這種方式調用我的異步函數:

const response = await myFunction();

這是函數的定義:

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);
        });
    });
}

如果發生這種情況,我應該如何正確攔截錯誤? 即當我等待函數時我如何管理它?

編輯:根據要求,更完整的片段:

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 }

使用嘗試/捕獲:

let response;
try {
   response = await myFunction();
} catch (error) {
  // Handle error here.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM