简体   繁体   English

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

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

I'm making an app using the nano npm module with nodejs, one of my async functions is intended to create an object in Cloudant but I'm not pretty sure how to handle a Promise.resolve with a callback which is an important part of the response which is supposed my server has to respond. 我正在使用带有nodejs的nano npm模块制作一个应用程序,我的一个异步函数旨在在Cloudant中创建一个对象,但我不太确定如何使用回调处理Promise.resolve,这是该程序的重​​要组成部分应该是我的服务器必须响应的响应。

I do well with creating the document but the next part is to check if there was an error trying to do it, so if there is an error I'd like my server to return an object with the classic error message. 我在创建文档方面做得很好,但是下一部分是检查尝试执行该操作是否有错误,因此如果有错误,我希望服务器返回带有经典错误消息的对象。

This is my code: 这是我的代码:

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;

} }

If I try to run this code the output is: 如果我尝试运行此代码,则输出为:

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

The first printed object is because the code reached the part where I assign the response object with the status code 201 but the second part doesn't recognize the value of 'response' and the line "return response;" 第一个打印对象是因为代码到达了我用状态代码分配响应对象的部分201,但是第二个部分却无法识别“响应”的值和“返回响应”行; actually doesn't return it, I've confirmed it with postman (it doesn't get a response). 实际上没有返回,我已与邮递员确认(它没有得到回复)。

I think the problem here is that I'm not handling correctly the .then() syntax, I've tried changing to a classic callback with: 我认为这里的问题是我没有正确处理.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));
    }
});

But it prints: 但它打印:

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

Which means the code is not getting into the callback (it's not printing 'failure' or 'ok' objects) 这意味着代码没有进入回调(没有打印“失败”或“确定”对象)

What I'm missing here?:( 我在这里想念的是什么?:(

nano provides promise-based API when a callback is omitted. 当省略回调时, nano提供基于promise的API。

This is not how errors are handled in promises. 这不是在Promise中处理错误的方式。 then callback has 1 parameter, there will be no err . then callback具有1个参数,将不会有err

It's expected that a promise is rejected in case there's an error. 可以预料,如果出现错误,诺言将被拒绝。 Promise.resolve is redundant when there's already a promise and is always redundant with async..await . Promise.resolve在已有承诺的情况下是多余的,而对于async..await则总是多余的。

It should be: 它应该是:

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