最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何在then()方法内发送响应,然后再发送另一个then()方法?

运维笔记admin12浏览0评论

如何在then()方法内发送响应,然后再发送另一个then()方法?

如何在then()方法内发送响应,然后再发送另一个then()方法?

exports.confirm_new_app = (req, res) => {

    //get the app
    AppReq.findOne({_id: req.body.appId})
    .then( (app) => {
        if (app) {
            //remove additional info(reqDate,reqUserId)
            app = app.toObject()
            delete app.reqDate
            delete app.reqUserId
            //add it to apps collection
            let newApp = new App(app)
            return newApp.save()
        } else {
            //how to send this response??????
            res.status(404).json({
                message: "No application with the provided app Id!"
            })
        }
    })
    .then( (savedApp) => {
        //remove the savedApp from appReq collection
        return AppReq.remove({_id: savedApp._id})
    }).then( (removedApp) => {
        res.status(200).json(removedApp)
    })
    .catch( (err) => {
        res.status(500).json({
            error: err
        })
    })
}

在以上示例中,发送res.status(404).json({...})的正确方法是什么?当前代码将触发错误,因为它尝试发送两次响应!

回答如下:

如果有错误并想退出.then()链,则抛出错误。然后处理您的捕获中的错误。

所以代替

    else {
        //how to send this response??????
        res.status(404).json({
            message: "No application with the provided app Id!"
        })
    }

尝试:

    else {
        throw new Error('appId');
    }

然后抓住了:

.catch( (err) => {
    if (err.message === 'appId') {
        res.status(404).json({
            message: "No application with the provided app Id!"
        })
    } else {
        res.status(500).json({
            error: err
        })
    }
})
发布评论

评论列表(0)

  1. 暂无评论