Node/Express return 主函数出错?

Node/Express return error to main function?

我的情况是 POST 路由多次调用一个函数。如果 调用的函数 return 出错 ,我希望请求 return 出错,但我不确定如何实现此目的。看这张图片:

这是我的代码:

function POSTcord(lat, lng) {
    axios
    .post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
        batteryLevel: 100,
        longitude: lng,
        latitude: lat
    })
    .then(res => {
        console.log(`statusCode: ${res.status}`)
    })
    .catch(error => {
        console.error(error.message);
    })
}

router.post('/test', async (req, res) => {
    let passedCords = req.body;
    try {
        for (const cord of passedCords) {
            POSTcord(cord.lat, cord.lng);
        }
        res.status(200).json({status:"success", message: "hello!"});
      } catch (err) {
        console.error(err.message);
        res.status(500).send("Server error");
      }
});

如果函数 POSTcord 在循环中某处捕获错误,我希望路由 /test 到 return 出错。对此有什么想法吗?我想我可以将 res 传递给 POSTcord 函数,但这没有用。感谢任何输入:)

您需要 return Promise 并确保错误为 thrown/rejected:

要么这样做:

function POSTcord(lat, lng) {
    return axios // <--------------- THIS IS VERY IMPORTANT
    .post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
        batteryLevel: 100,
        longitude: lng,
        latitude: lat
    })
    .then(res => {
        console.log(`statusCode: ${res.status}`)
    })
    .catch(error => {
        console.error(error.message);
        throw error; // <----------- ALSO DO THIS
    })
}

或者这样做:

function POSTcord(lat, lng) {
    return axios // <--------------- THIS IS VERY IMPORTANT
    .post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
        batteryLevel: 100,
        longitude: lng,
        latitude: lat
    })
    .then(res => {
        console.log(`statusCode: ${res.status}`)
    })
    // DON'T CATCH THE ERROR!!
}

那么你需要做的就是await得到错误:

router.post('/test', async (req, res) => {
    let passedCords = req.body;
    try {
        for (const cord of passedCords) {
            await POSTcord(cord.lat, cord.lng); // DO THIS FOR CATCH TO WORK
        }
        res.status(200).json({status:"success", message: "hello!"});
      } catch (err) {
        console.error(err.message);
        res.status(500).send("Server error");
      }
});

如果您想并行调用 POSTcord(),您可以 await 使用 Promise.all():

router.post('/test', async (req, res) => {
    let passedCords = req.body;
    try {
        let promises = [];
        for (const cord of passedCords) {
            let p = POSTcord(cord.lat, cord.lng);
            promises.push(p);
        }

        await Promise.all(promises); // DO THIS FOR CATCH TO WORK

        res.status(200).json({status:"success", message: "hello!"});
      } catch (err) {
        console.error(err.message);
        res.status(500).send("Server error");
      }
});