【问题标题】:Bug: A return won't stop execution when a reject is received and handled错误:收到并处理拒绝时,退货不会停止执行
【发布时间】:2022-02-11 09:47:17
【问题描述】:

重现步骤:

第 1 步。VSC,F1 创建自动生成 Azure 函数 (AF)。

第二步,index.js,将其替换为MS AF Js developer guide

module.exports = async function (context) 
{
    const good = await db.pgTest({})  // this call will receive a Promise.reject, see below
        .catch
        (
            ce => 
            {
                context.res = {status: 401, body: ce};
                return;   // execution supposed end, but it goes on
            }
        );
    var x = good[0]["column1"];  
    // execution continues to above line even .catch() has a return
    // 'good' will have an array when db.pgTest() succeeds, now is 'undefined'
    // but strangely terminal doesn't print out exception like:
    // Exception: TypeError: Cannot read property '0' of undefined, Stack: TypeError: Cannot read property '0' of undefined    

}

步骤 3. 创建 db.pgTest(),一个标准的 Promise。可以是我正在使用的任何数据库调用pg-promise:

const pgTest = (param) =>
{
    return new Promise((resolve, reject) =>
    {
        var sql = 'select * from schema.nonexits()';  // simply call a non-exists function to raise a runtime error
        db.any(sql)
        .then
        (
            good => resolve(good),
            bad => 
            {
                reject({status: 401, bad: bad});
            }
        )
        .catch
        (
            ce =>
            {
                reject({status: 402, bad: ce});   // because .then(..., bad=>...) this block is never reached. 
            }
        )
    }
    );
}

环境:

Version: 1.63.1 (system setup)
Commit: fe719cd3e5825bf14e14182fddeb88ee8daf044f
Date: 2021-12-14T02:13:54.292Z
Electron: 13.5.2
Chromium: 91.0.4472.164
Node.js: 14.16.0
V8: 9.1.269.39-electron.0
OS: Windows_NT x64 10.0.19044
Azure Functions Extension: v1.6.0

步骤 4. F5 并点击 URL。

更新 我对return 的问题是关于index.js,阻止ce => { ... return; }。我忽略了这个块确实是一个函数。

【问题讨论】:

  • 它从它所在的函数返回。如果你想停止执行,你可能不应该捕获那个异常,或者至少重新抛出它。
  • @tkausl No .catch 将导致 UnhandledPromiseRejectionWarning 中止执行,客户端将永远不会收到任何响应。

标签: azure-functions


【解决方案1】:

这里我们将PgTest()函数的回调请求放在了一个Promise包装器Promise( (resolve, reject) => { //callback function})中。这个包装器允许您调用 pgTest 函数,就像使用 .catch() 方法的承诺一样。当调用 pgTest 时,它会执行对 API 的请求并等待 resolve() 或 reject() 语句执行.在回调函数中,您只需将检索到的数据传递给 resolve 或 reject 方法。检查here

.catch 是 Promise 的包装函数,可用于捕获 .then/inside the 块内发生的任何异常。

因此,将执行返回,并且将退出包装函数。因为 .catch 包装函数可以处理 .Catch 块中的每个异常

更新:

更多信息请参考here

【讨论】:

  • 请阅读return是什么
  • 请查看更新后的答案。
  • 我对@9​​87654335@的问题是关于index.js,阻止ce => { ... return; }。我忽略了这个块确实是一个函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 2015-07-14
  • 1970-01-01
  • 2021-05-27
  • 2020-12-26
  • 2020-08-02
  • 1970-01-01
相关资源
最近更新 更多