使用 await 在 try/catch 块中声明一个常量

A. *_*Lau 5 javascript node.js

所以我目前有这个:

var item_id
try {
    item_id =
        await
            (async function () {
               // code
            })();
} catch (error) {

}
Run Code Online (Sandbox Code Playgroud)

但我更喜欢item_id作为一个常量。鉴于该节点要求我处理承诺拒绝,将 await 值分配给 const 的最佳方法是什么

例如错误:

[0] (node:77118) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: details[Symbol.iterator] is not a function
[0] (node:77118) [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.
Run Code Online (Sandbox Code Playgroud)

异步代码

await
    (async function () {
        const query = `
            INSERT INTO item (list_id)
            SELECT 
                ?
            FROM
                list
            WHERE
                id = ?
                AND
                user_id = ?
            LIMIT 1;
        `

        const results =
            await
                doQuery({
                    inputs: [
                        list_id,
                        list_id,
                        req.session.user.id
                        // 10
                    ],
                    query,
                    error_message: "item create mysql error"
                })
        return results.insertId === 0 ? false : results.insertId
    })();
Run Code Online (Sandbox Code Playgroud)

查询

function doQuery({ query, inputs, error_message, res = null }) {
    return (
        new Promise(function (resolve, reject) {
            db.query(query, inputs, function (err, results, fields) {
                if (err) {
                    console.trace(chalk.green(db.sql))
                    console.log()
                    handleError({ error: err, error_message, res })
                    reject(err)
                    return
                }

                resolve(results)
            })
        })
    )
}
Run Code Online (Sandbox Code Playgroud)

处理错误

function handleError({ error, message, res }) {
    console.trace(chalk.yellow(message))
    console.trace(chalk.red(error))
    console.log()

    if (res) {
        res.send({
            error: true,
            success: false,
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

这是一个众所周知的问题,已在别处讨论过。

您的选择包括:

  1. 就像您所做的那样在外部声明item_idwith let。没有错。

  2. 根据您想对 做item_id什么,在try/catch块内执行此操作,允许您const item_id;在try.

  3. 确保您确实需要一个try/catch. 请记住,async函数内部抛出的任何错误都会自动转化为对函数返回的承诺的拒绝。你不必(在可能的情况下也不想)抓住它;相反,在更高级别处理错误。Node“要求你处理承诺拒绝”并不意味着你必须在它发生的地方处理它;您可以在任何更高级别处理它。请记住,catch在这里出现错误将使异步函数回到“快乐路径”(除非您重新抛出)并且调用函数将无法知道存在错误。

  4. 在某些情况下,如果您重新使用 promises 和.catch(),您的代码将更具可读性,如

    const item_id_promise = async function () {}();
    
    item_id_promise.catch(...);
    
    Run Code Online (Sandbox Code Playgroud)

    或者甚至可能只是

    return (async function() { }()).catch(...)
    
    Run Code Online (Sandbox Code Playgroud)

但实际上你的问题有没有关系await,async或者承诺。它只是关于块内变量的块作用域,在这种情况下是一个try块。是的,const并且let是块范围的,因此范围是try子句。所以和其他任何事情一样,如果你想在try块外使用它们,你必须在try块外声明它们。或者,如果你真的不想在try块外声明它们,你不能在try块外使用它们,所以你必须安排只在块内使用它们,如果可能的话。


fuz*_*uzz 1

按照@torazaburo的建议:

const item_id = async function () {
  // code
  return 1337; // return your expected item id
}();
item_id.catch(function (e) {
  console.error(e);
});
Run Code Online (Sandbox Code Playgroud)

  • 这如何解决任何问题?这里的“item_id”是一个函数,而不是一个值。 (2认同)