簡體   English   中英

承諾拒絕可能未處理的錯誤:

[英]Promise reject Possibly unhandled Error:

我有一個使用數組執行某些操作的函數。 當數組為空時我想拒絕它。

舉個例子

myArrayFunction(){
        return new Promise(function (resolve, reject) {
           var a = new Array();
           //some operation with a
           if(a.length > 0){
               resolve(a);
           }else{
               reject('Not found');
           }           
        };
}

拒絕操作發生時,我收到以下錯誤。 可能未處理錯誤:未找到

但是,當調用myArrayFunction()時,我有以下catch。

handlers.getArray = function (request, reply) {
    myArrayFunction().then(
        function (a) {
            reply(a);
        }).catch(reply(hapi.error.notFound('No array')));
};

什么是拒絕承諾,抓住拒絕和回應客戶的正確方法?

謝謝。

.catch將函數作為參數,但是,您傳遞的是其他內容。 當你沒有傳遞一個函數來捕獲時,它將默默無法做任何事情。 愚蠢,但這是ES6承諾的。

由於.catch沒有做任何事情,拒絕變得無法處理並報告給您。


修復是將函數傳遞給.catch

handlers.getArray = function (request, reply) {
    myArrayFunction().then(function (a) {
        reply(a);
    }).catch(function(e) {
        reply(hapi.error.notFound('No array')));
    });
};

因為您正在使用catch all,所以錯誤不一定是No array錯誤。 我建議你這樣做:

function myArrayFunction() {
    // new Promise anti-pattern here but the answer is too long already...
    return new Promise(function (resolve, reject) {
            var a = new Array();
            //some operation with a
            if (a.length > 0) {
                resolve(a);
            } else {
                reject(hapi.error.notFound('No array'));
            }
        };
    }
}

function NotFoundError(e) {
    return e.statusCode === 404;
}

handlers.getArray = function (request, reply) {
    myArrayFunction().then(function (a) {
        reply(a);
    }).catch(NotFoundError, function(e) {
        reply(e);
    });
};

哪些可以進一步縮短為:

handlers.getArray = function (request, reply) {
    myArrayFunction().then(reply).catch(NotFoundError, reply);
};

另請注意以下區別:

// Calls the method catch, with the function reply as an argument
.catch(reply)

// Calls the function reply, then passes the result of calling reply
// to the method .catch, NOT what you wanted.
.catch(reply(...))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM