【问题标题】:Why does my async js/nodejs function skip a big part?为什么我的异步 js/nodejs 函数跳过了很大一部分?
【发布时间】:2021-07-27 16:57:22
【问题描述】:

所以我调用以下函数:

async function sql_func(){
    console.log('anothertest')
    async () => {
        console.log('third test')
        try {
            await sql.connect('heres the connection data')
            const result = await sql.query`heres a query`
            console.log(result) 
        } catch(err) {
            console.log(err)
        }
    }
}

第一个控制台日志 anothertest 被记录,但 async () => {} 内的部分被完全跳过。调试时我看到它只是从 async() => { 线直接跳到右括号 }

我做错了什么?

【问题讨论】:

  • 您定义了一个 lambda 函数,但实际上并没有调用它。
  • 想象一下,如果你愿意,在你的代码中你从未调用过sql_func() ...结果将是相同的,除了即使执行的一行也不会被执行
  • @bravo 那么我该如何调用 () => 函数呢?我现在不知道,所以我以前用过。
  • 下面有一个答案 - 但是 - 你为什么要创建那个 IIFE?
  • @Bravo 我不知道,今天有点休息,今天做了很多不必要的错误。感谢您的回复。

标签: javascript node.js async-await


【解决方案1】:
async function sql_func() {
    console.log('anothertest')
    await sql.connect('heres the connection data')
    const result = await sql.query`heres a query`
    console.log(result)
    return result
}

在您的示例中,无需定义另一个函数:async () => { }。这个函数永远不会被调用。当一个承诺被拒绝时,异步函数也处理所有承诺和拒绝。您可以在主函数级别执行的操作:

const result = await sql_func().catch(error => // do something)
// Or with try / catch

如果您想要不同的错误消息(例如:隐藏真正的错误/堆栈跟踪):

async function sql_func() {
    console.log('anothertest')

    await sql.connect('heres the connection data').catch(error =>
        Promise.reject('DB Connection error')
    )
 
    const result = await sql.query(`heres a query`).catch(error =>
        Promise.reject('Query failed')
    )

    console.log(result)
    return result
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-10
    • 2020-02-27
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    相关资源
    最近更新 更多