Exceptions thrown in asynchronous functions handled synchronously

What occurs if an async function throws an exception synchronously?

For instance:

async function whatHappen () {
  throw new BombError()
  // no "await" here
}

try {
  whatHappen().catch(() => console.error('rejected'))
} catch (e) {
  console.error('thrown')
}

After testing this example in Babel, it appears that the throw is automatically caught and translated into a rejected promise, resulting in the message "rejected" being logged to the console.

However, does this accurately represent the official specification and how JavaScript engines will handle it? I attempted to understand the details from the technical proposal, but it is clear that the specification targets language implementers rather than users.

Is it a reliable assumption that async functions will consistently return a promise, or are there situations where they could synchronously throw an exception? Are there any instances where calling an async function without await necessitates the use of a try/catch block?

Answer №1

A Promise is always returned by an async function.

The document you referenced contains a statement at the start noting that:

During discussions on ES6, Deferred Functions were proposed as well. This proposal aligns with the same objectives, utilizing comparable or identical syntax, while leveraging control flow structures parallel to those of generators and utilizing promises for the return type, rather than defining bespoke mechanisms.

(My emphasis)

It is unnecessary to enclose an async function in a try/catch block since it does not throw synchronous errors.

PS: I just discovered that Chrome Canary and MS Edge have integrated async/await behind a flag, allowing you to test it there too.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on connecting input fields to a modal in AngularJS

My form is set up with a Customer and its properties populating input fields. When the user needs to change the Customer, they click on the CustomerName input which triggers a modal to open with a Customer List for selection. The chosen selection should th ...

Encountering unanticipated undefined elements while incorporating map in JSX

I'm attempting to dynamically generate <Audio> components using the map method: import React, { useState, useRef, createRef } from 'react'; const audios = [{ src: '/fire.mp3' }, { src: '/crickets.mp3' }]; function ...

Switch Selector for React Native

Although it may seem simple, I'm having trouble getting a function to automatically switch between the "user" and "business" options on the switch selector without requiring manual input from the user. I attempted to use: const switchRef = useRef(nu ...

Encountering a PDF loading error when integrating ReactPDF in a React project

Having trouble trying to display a PDF file using the PdfReact component. Every time I attempt to load the PDF, I encounter the following error: Warning: Ignoring invalid character "114" in hex strinpdf.worker.js:342 Warning: Ignoring invalid character " ...

Incorporating dynamic SVGs in real-time into a Vue.js application

I have been working on an old project that was originally built with messy jQuery code many years ago. I am now looking to upgrade it by incorporating a JavaScript framework for better scalability, state management, and overall cleaner, more maintainable c ...

Why is the image not appearing in the Popover?

When hovering over, the popover only shows the title and not the image. Snippet of Code: <script type="text/javascript"> $(document).ready(function(){ var img ='<img src="/assets/Excel_1.png">'; $("#blob").popover({ title: ' ...

Object placed at the mouse position is shifted from its original location

I am working with ThreeJS in conjunction with MindAR, attempting to position an object where I click on the screen using my mouse. const mousePositionX = (e.clientX / window.innerWidth) * 2 - 1; const mousePositionY = -(e.clientY / window.innerHeight) * 2 ...

The sendFile function requires the input of an absolute file path

I am encountering an issue with the sendFile() method. It appears to be overlooking files in the public folder and instead searching on the C drive, despite having set a static path. This observation arose when comparing the behavior of the index.ejs file ...

AJAX working concurrently across multiple threads

After learning that JavaScript is single-threaded (as discussed in this question: If Javascript is not multithreaded, is there any reason to implement asynchronous Ajax Queuing?), I started to explore how this concept applies to my developed application. H ...

How to exchange variables and trigger events between jQuery and C# using AJAX

Hey there! So I've got this jQuery snippet that's using jqvmaps to display a world map and interact with it: <script type="text/javascript" lang="js> $(document).ready(function(){ jQuery('#vmap').vectorMap( ...

Searching for text within a URL using JavaScript

In my menu, there are different classes and one of them is "photos" for both the photos button and the photos page. When clicking on the photos button, the URL changes to /index.php?t=photos. What is the most effective way to detect if the URL contains ?t= ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Convert the PHP array to JSON format and display it using the AJAX success function

Is there a way to convert the following array into JSON using PHP and retrieve it via AJAX? array(4) { ["START_TIME"]=> string(19) "2017-12-19 08:34:01" ["END_TIME"]=> string(19) "2017-12-19 10:34:07" ["DESCRIPTION"]=> string(30) ...

Retrieving input value in an Android WebView

I recently attempted to extract the value of an input type and store it as a string within my Android WebView. Unfortunately, I couldn't find a straightforward solution. The snippet of code in my HTML file is as follows: <input class="input100 ...

How can I restrict the draggable space? It is only working on the top and left sides, but I want to disable it on the right and bottom

Attempting to prevent the draggable items from overflowing beyond the body. Succeeded in limiting movement on the top and left sides. Encountering difficulty restricting motion on the right side and bottom. e.pageX -= e.offsetX; e.pageY -= e.offsetY; ...

Tips for retrieving a link href with selenium

Here is a link from the webpage I am automating: https://i.sstatic.net/kfFEa.png Upon inspecting its element, I found this: https://i.sstatic.net/v501c.png I'm interested in extracting only /console/agent_invoices/2297294 which is in the href ...

On which platforms does RegEx function? It seems to work in both the Browser and the Node Terminal, but what about in

I'm encountering a strange issue with a code snippet that uses regex. It functions perfectly in the browser terminal and Node Terminal, but when I write it into a file and use node to execute it, I receive an error saying that the output is null. I&ap ...

Setting the image path using setAttribute in JavaScript: A step-by-step guide

Trying to establish a pathway to an image in my local storage using a setAttribute approach seems to be resulting in an error indicating that the image cannot be found. Here is a snippet of the code I am working with: if (shipLocation[0][0] == shipLocatio ...

Prevent the page from refreshing when a value is entered

I currently have a table embedded within an HTML form that serves multiple purposes. The first column in the table displays data retrieved from a web server, while the second column allows for modifying the values before submitting them back to the server. ...

Exploring each item within oData: A guide

After writing the code statement above, I am able to see the attached image. Now, my challenge is accessing the "label" property inside each object. How can I iterate through these objects and retrieve their "label" properties? item.getModel().oData; I a ...