declaring a const inside a try/catch block with await

typescript async/await try catch
await javascript
set variable with await
c# await variable
async/await global variable
save async/await response on a variable
async variable
assign result of async function to variable

So I currently have this:

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

}

But I'd much prefer having item_id as a const. What's the best way to assign the await value to a const, given that node requires me to handle promise rejection

e.g. Errors:

[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.

Async code

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
    })();

doQuery

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)
            })
        })
    )
}

handleError

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,
        })
    }
}

This is a well-known problem which has been discussed elsewhere.

Your options include:

  1. Just declaring item_id with let at the outer level as you have done. Nothing wrong with that.

  2. Depending on what you want to do with item_id, do that inside the try/catch block, allowing you to declare const item_id; inside the try.

  3. Make sure you really need a try/catch. Remember that any error thrown inside an async function will automatically translate into a rejection of the promise being returned by the function. You don't have to (and in may cases don't want to) catch it; instead, handle the error at a higher level. Node "requiring you to handle promise rejection" does not mean you have to handle it right here where it occurs; you can handle it at any higher level. Remember that catch'ing the error here will put the async function back on the "happy path" (unless you re-throw) and the calling function will have no way of knowing there was an error.

  4. In some cases, your code will be more readable if you go back to using promises, and .catch(), as in

    const item_id_promise = async function () {}();
    
    item_id_promise.catch(...);
    

    or possibly even just

    return (async function() { }()).catch(...)
    

But actually your question has nothing to do with await, async, or promises. It's just about block-scoping of variables inside blocks, in this case a try block. Yes, const and let are block-scoped, and therefor are scoped to the try clause. So like anything else, if you want to use them outside the try block, you have to declare them outside the try block. Or, if you really don't want to declare them outside the try block, you can't use them outside the try block, so you have to arrange to use them only inside it, if that's possible.

Correct TryCatch Syntax Using Async/Await, If you want to catch and handle errors only from the promise, you have three choices: Declare the variable outside, and branch depending on whether there was an exception let createdUser; // or use `var` inside the block try { createdUser = await this. async function someAsyncFunction(){ const createdUser = await this. Regarding variables, perhaps we should allow them as well and so disable this rule and enable block-scoped-var, instead? Disable checking variable declarations when using block-scoped-var or if declaring variables in nested blocks is acceptable despite hoisting.

You could define your function in another scope using the power of Promises such as:

async function foo(bar) {
    return new Promise((resolve, reject) => {
         if(bar === 'baz') {
              resolve(bar); // Resolve this promise
         } else {
              reject(); // Reject this promise
         }
    });
}

foo('baz').then(baz => {
    // Do something with 'baz', the result of the resolved promise
}).catch(error => {
    // The promise is rejected, process an error here
});

Learn Vue.js: The Collection, This is where the axios library comes in that we installed previously. within async/await is to wrap everything in a try/catch block: export const api = { getWord​:  How to write async await without try-catch blocks in Javascript ES7 Async/await allows us as developers to write asynchronous JS code that look synchronous. In current JS version we were introduced to Promises, that allows us to simplify our Async flow and avoid Callback-hell.

Following @torazaburo's suggestion:

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

Vue.js: 11 Practical Projects, const res = await axios.get(baseURL); return res.data; }), deleteWord: with errors within async/await is to wrap everything in a try/catch block: export const api  Constants are block-scoped, much like variables defined using the let statement. The value of a constant can't be changed through reassignment, and it can't be redeclared. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project,

JavaScript for Modern Web Development: Building a Web Application , firstFn() .then(alert); // 'first resolved' Await can be used along with any the try​catch block as shown in following example: const asyncFnCall = async () => { try​  From inside a try block, initialize only variables that are declared therein. Otherwise, an exception can occur before the execution of the block is completed. For example, in the following code example, the variable n is initialized inside the try block.

How to Throw Errors From Async Functions in Javascript?, How to Throw Errors From Async Functions in Javascript: what you will learn in Javascript; how to test exception from async functions with Jest "use strict"; const assert = require("assert"); const upperCase = require(". The await operator is used to wait for a Promise. It can only be used inside an async function. A Promise or any value to wait for. Returns the fulfilled value of the promise, or the value itself if it's not a Promise. The await expression causes async function execution to pause until a Promise is settled, that is fulfilled or rejected, and to

Deeply Understanding JavaScript Async and Await with Examples, Due to JavScript's asynchronous nature, a callback is required in many… Notice the use of async keyword at the beginning of the function declaration. It is internally transformed into const a = await Promise.resolve(9); . However, we can use try-catch in async functions to handle errors synchronously. In the case of an error, it propagates as usual, from the failed promise to Promise.all, and then becomes an exception we can catch inside the catch block. Key takeaways. async and await enable us to write asynchronous code in a way that looks and behaves like synchronous code. This makes the code much easier to read, write, and reason about.

Comments
  • Are you handling the error, or ignoring it, leaving item_id as undefined?
  • @MarcosCasagrande I actually have an error handler inside the async function which is imported from another file
  • Can you post a little more of your code? So we get the full grasp of what you have, and how it can be improved.
  • @MarcosCasagrande updated, hopefully enough
  • yeah, I've just chosen to wrap the entire thing in a try... catch
  • But it's a safe assumption that entire thrust of the OP's question related to using async/await and catching errors by means of try/catch blocks around that.
  • This looks like you're assigning a function to item_id. This lambda function isn't actually being invoked. Am I reading this incorrectly?
  • I still need the item_id to be retrieve synchronously because I need it for inserting other rows later on.
  • How does this solve anything? item_id here is a function, not a value.