繁体   English   中英

如何使用Node.js回调处理Promise?

[英]How to handle a promise with a callback with nodejs?

我正在使用带有nodejs的nano npm模块制作一个应用程序,我的一个异步函数旨在在Cloudant中创建一个对象,但我不太确定如何使用回调处理Promise.resolve,这是该程序的重​​要组成部分应该是我的服务器必须响应的响应。

我在创建文档方面做得很好,但是下一部分是检查尝试执行该操作是否有错误,因此如果有错误,我希望服务器返回带有经典错误消息的对象。

这是我的代码:

exports.createMeeting = async (body) => {
var response;
object = {"name": "Billy Batson"}
console.log("-------------")

//Trying to insert the document
response = await Promise.resolve(db.insert(object).then((body, err) => {
        //This is the part I'm trying to check if the db.insert did fail
        if (err) {
            response = {
                message: 'Failure',
                statusCode: '500',
            }
            console.log(JSON.stringify(response));
        } else {
            response = {
                message: 'Ok',
                statusCode: '201',
            }
            console.log(JSON.stringify(response));
        }
    }));
}
console.log("******* ", JSON.stringify(response));
return response;

}

如果我尝试运行此代码,则输出为:

-------------
{"message":"Ok","statusCode":"201"}
*******  undefined

第一个打印对象是因为代码到达了我用状态代码分配响应对象的部分201,但是第二个部分却无法识别“响应”的值和“返回响应”行; 实际上没有返回,我已与邮递员确认(它没有得到回复)。

我认为这里的问题是我没有正确处理.then()语法,我尝试使用以下方法更改为经典回调:

response = await Promise.resolve(db.insert(object),(body, err) => {
    if (err) {
        response = {
            message: 'Failure',
            statusCode: '500',
        }
        console.log(JSON.stringify(response));
    } else {
        response = {
            message: 'Ok',
            statusCode: '201',
        }
        console.log(JSON.stringify(response));
    }
});

但它打印:

-------------
*******  {"ok":true,"id":"502c0f01445f93673b06fbca6e984efe","rev":"1-a66ea199e7f947ef40aae2e724bebbb1"}

这意味着代码没有进入回调(没有打印“失败”或“确定”对象)

我在这里想念的是什么?:(

当省略回调时, nano提供基于promise的API。

这不是在Promise中处理错误的方式。 then callback具有1个参数,将不会有err

可以预料,如果出现错误,诺言将被拒绝。 Promise.resolve在已有承诺的情况下是多余的,而对于async..await则总是多余的。

它应该是:

try {
    const body = await db.insert(object);
    response = {
        message: 'Ok',
        statusCode: '201',
    }
} catch (err) {
    response = {
        message: 'Failure',
        statusCode: '500',
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM