node.js - promise 拒绝时从函数返回

标签 node.js promise

我有两个功能。一个调用某个东西,另一个从它调用,asyncfunc。我的问题是,如果在 asyncfunc 函数内部抛出错误,我想停止执行函数的其余部分并返回。我发现如果我在 catch 中重新抛出错误,我可以得到这种行为,但之后我需要添加另一个 catch。

那么如果任何 promise 被拒绝,我如何从函数返回? (在这种特定情况下,它们是一个接一个,所以我想我可以使用 .then,但如果它们没有嵌套,我想要相同的结果)。

async function something()
{
    await asyncfunc().catch(e => console.error(e));
}

async function asyncfunc()
{
    await some_promise.catch(err => { throw new Error(err) }); // Error gets swallowed unless I add another catch

    await some_promise2.catch(err => { throw new Error(err) }); // Error gets thrown here, return and don't execute promise 3

    var data = await some_promise3.catch(err => { throw new Error(err) });

    return data;
}

最佳答案

您可以在 something() 函数中捕获错误,并且您的 asyncFunc 可以在抛出时链接以传播错误:

function something()
{
    // You dont need to call async/await, if you are not returning 
    // and this function only has one call.
    asyncfunc().catch(e => console.error(e));
}

// Notice I have removed "async"
function asyncfunc()
{
    // its a simple case of chain of Promises.
    // to execute it serially you can chain it like this;

    return some_promise
         .then(some_promise2)
         .then(some_promise3)
         .catch(error => {
             // you can do something like 'log' it
             throw error;
         })
}

关于node.js - promise 拒绝时从函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899410/

相关文章:

javascript - Node.js 对象不是函数 - module.exports

mysql - Mysqljs 中的转义值

javascript - 连接到 Promise 的 .then 方法

javascript - 收到警告: promise 以非错误被拒绝:Turbo中的[object String]

node.js - 在 Node.js Express 路由/ Controller 中对基于 Promise 的代码进行单元测试

javascript - 为什么 node.js 会忽略 package.json 文件中的 "type"设置?

javascript - 使用时间戳 Node js从mongodb获取今天导入的数据

node.js - Express.js : res. render() 包装在 promise 链中时不发送数据

javascript - 作为一个整体解析具有 promise 属性的对象的更好方法?

javascript - Express 与浏览器结合使用 Node 同步