簡體   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