Search code examples
node.jspromisecallbackresponsenano

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.

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;" 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:

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?:(


Solution

  • nano provides promise-based API when a callback is omitted.

    This is not how errors are handled in promises. then callback has 1 parameter, there will be no 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.

    It should be:

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