What sets returning a promise from async or a regular function apart?

I have been pondering whether the async keyword is redundant when simply returning a promise for some time now.

Let's take a look at this example:

async function thePromise() {
    const v = await Inner();
    return v+1;
}

async function wrapper() {
    return thePromise();
}

I am questioning if, for the wrapper function, since it does not wait inside the promise for resolution, the async keyword is unnecessary. Shouldn't we just use:

function wrapper() {
    return thePromise();
}

The main downside to this approach is that it hides the fact that we are using promises, but other than that: is there any real distinction between returning a promise from an asynchronous function or a regular function?

Answer №1

Take a look at this straightforward example: -

let person = {
    name: 'Jessica'
}
// Creating a promise
let myPromise = new Promise((resolve, reject) => {
    if (person) {
        resolve(person.name==='Jessica')
    }
    else {
        reject(new Error("Oops!"))
    }
}
)

function handlePromise(){
    return myPromise;
}
// Using the promise
handlePromise().then(res => {
    if (res) {
        console.log("Promise fulfilled")
        console.log(person)
    }
    else {
        console.log("Promise rejected")
    }
})

Answer №2

In the realm of JavaScript, there is no concept of a Promise within a Promise; they are essentially the same.

// code snippet 1
promise1.then(() => {
  //...
  return promise2;
}).then(f);

// This is equivalent to code snippet 2

promise1.then(() => {
  //...
  return promise2.then(f);
});

A similar principle applies to async functions. When a promise is returned from an async function, it is akin to returning the awaited expression.

// code snippet 3
async () => {
  // ...
  return p;
}

// This is equivalent to code snippet 4
async () => {
  // ...
  return await p;
}

It's important to mention that this equivalence does not extend to arrays of promises and similar scenarios. In such cases, you can utilize Promise.all to transform the array of promises into a single promise or create custom solutions for other data structures.

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

Update the data table after a new file has been uploaded

As a novice web developer, I embarked on my first project using Vue. In this project, I created a form for file uploads in Vue 2 and Laravel. If you want to take a look at the full code: View: https://pastebin.com/QFrBfF74 Data table user file: https:/ ...

Issues with the audio on ExpressJS video streaming can be quite vexing

After multiple attempts to run an ExpressJS web server that serves videos from my filesystem, I've encountered a frustrating issue. Whenever a video is played, there are constant popping sounds and eventually the audio cuts out completely after 3-10 m ...

Pushing state history causes browser back and forward button failure

I'm currently utilizing jQuery to dynamically load content within a div container. On the server side, the code is set up to detect if the request is being made through AJAX or GET. In order to ensure that the browser's back and forward buttons ...

Tips for extracting dynamically loaded content from a website using Node.js and Selenium?

I'm currently encountering some challenges when trying to scrape a website that utilizes react for certain parts of its content, and I'm unsure about the reason behind my inability to extract the data. Below is the HTML structure of the website: ...

Tips for adjusting the size of an HTML canvas to fit the screen while preserving the aspect ratio and ensuring the canvas remains fully visible

I'm working on a game project using HTML canvas and javascript. The canvas I am using has dimensions of 1280 x 720 px with a 16:9 aspect ratio. My goal is to have the game displayed at fullscreen, but with black bars shown if the screen ratio is not 1 ...

Retrieve the parseJSON method using a string identifier

I am trying to serialize a C# const class into name-value pairs, which I need to access by their string names on the client side. For example: return $.parseJSON(constantClass).property; This approach is not working as expected. Is there any alternative ...

The error message "UnhandledPromiseRejectionWarning: Error: ENOTEMPTY: directory not empty" typically occurs

Struggling to successfully run the build using npm run build. Encountering the following error: UnhandledPromiseRejectionWarning: Error: ENOTEMPTY: directory not empty, rmdir '/var/www/html/abhinav/png-react/png-compressor/build/static' ...

It appears that Vivus JS is having difficulty animating specific <path> elements

I've been experimenting with the Vivus JS library, which is fantastic for animating paths such as drawing an image. However, I'm facing an issue where my SVG icon should animate to a 100% line-width, but it's not working as expected. Interes ...

Tips for utilizing Vue.js techniques to assign values to data properties

As a newcomer to Vue.js, I am in the process of learning how to display data retrieved from a server. In my new Vue app, I have defined a method: methods: { getData: function() { // making a request, parsing the response and pushing it to the array. ...

Node.js (Express), passport.js, mongoose.js, and Android app all have in common the HTTP Error 307 - Temporary redirect

I am currently constructing a REST Api using Node.js (Express.js and Moongose.js). I have a single post route that takes JSON data and redirects it to the signup page (/app/signup) if the user is a first-time user (not found in the database), or to the log ...

The function slice is not a method of _co

I'm attempting to showcase the failedjobs array<any> data in a reverse order <ion-item *ngFor="let failjob of failedjobs.slice().reverse()"> An issue arises as I encounter this error ERROR TypeError: _co.failedjobs.slice is not a fu ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

Mixing success and error states can lead to confusion when using jQuery and Express together

I've been struggling with a simple question that's been on my mind for quite some time. Despite my searches, I haven't found a similar query, so I apologize if it seems too basic or repetitive. The scenario involves an API route (Express-ba ...

Exploring AngularJS tab navigation and injecting modules into the system

Two separate modules are defined in first.js and second.js respectively: first.js var app = angular.module('first',['ngGrid']); app.controller('firstTest',function($scope)) { ... }); second.js var app = angular.mo ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...

Can you explain the contrast between the functions 'remove' and 'removeChild' in JavaScript?

I have recently coded an HTML page in order to gain a better understanding of how element removal functions. Code: <html> <head> <script> var childDiv = null; var parent1 = null; var parent2 = null; function ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Display two images consecutively within a single img tag

My goal is to display two images using a single <img /> tag. The first small image will be loaded and shown using the src attribute, while the second large image will be contained within the data-src attribute. Only one image will be displayed at a t ...

Dealing with the issue of receiving raw JavaScript in the .ajax error function even when receiving a 200

I am encountering an issue with a jQuery.ajax() call to a third-party product. The POST request is successful, returning a 200 OK status code, but instead of executing the success function, it redirects to the error function. The response variable displays ...