最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

获得UnhandledPromiseRejectionWarning尽管有几个`try`

运维笔记admin10浏览0评论

获得UnhandledPromiseRejectionWarning尽管有几个`try`

获得UnhandledPromiseRejectionWarning尽管有几个`try`

我正在使用包含其API的第三方模块。我有以下代码:

const api = require('3rdpartyapi');

 async function callAPI(params) {
  try {
    let result = await api.call(params);
    return result;
  }
  catch(err) {
    throw err;  //will handle in other function
  }
 }
 
 async function doSomething() {
  try {
    //...do stuff
    let result = await callAPI({a:2,b:7});
    console.log(result);
  }
  catch(err) {
    console.error('oh no!', err);
  }
}
回答如下:

重点是等待只将“第一层”拒绝转换为错误,但是承诺内部可能有承诺,并且它们的库可能无法捕获内部的拒绝。我做了一个概念证明3rdpartyapi,可以触发你看到的行为:


(async function () {

// mock 3rdpartyapi
var api = {
    call: async function(){
        await new Promise((resolve, reject) => {
            // why wrap a promise here? but i don't know
            new Promise((innerResolve, innerReject) => {
                innerReject('very sad'); // unfortunately this inner promise fail
                reject('this sadness can bubble up');
            })
        })
    }
};

// your original code
async function callAPI(params) {
    try {
        let result = await api.call(params);
        return result;
    } catch (err) {
        throw err; //will handle in other function
    }
}

async function doSomething() {
    try {
        //...do stuff
        let result = await callAPI({
            a: 2,
            b: 7
        });
        console.log(result);
    } catch (err) {
        console.error('oh no!', err);
    }
}

doSomething();

})();

输出:

$ node start.js
oh no! this sadness can bubble up
(node:17688) UnhandledPromiseRejectionWarning: very sad
(node:17688) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:17688) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
发布评论

评论列表(0)

  1. 暂无评论