Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6637

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T08:23:08+00:00 2024-11-27T08:23:08+00:00

How to return a value from an asynchronous function (JavaScript)

  • 60k

Consider the following code. Suppose, you have a function, and what you want it to do is return a certain value after 5 seconds. So, you do this.

function getValue() {     setTimeout(() => {         return 42;     }, 5000); } 
Enter fullscreen mode Exit fullscreen mode

This won't work. Why? Because you're really returning from the callback function that is acting as the first argument of setTimeout. Essentially, what you're doing is this –

function getValue() {     function cb() {         return 42;     }      setTimeout(cb, 5000); } 
Enter fullscreen mode Exit fullscreen mode

As you can see, getValue isn't returning anything here.

You might face the same problem while making other similar asynchronous calls, like using the fetch API (or other Promise-based API) for example.

function getUserList() {     fetch("users.json")         .then(r => r.json())         .then(d => { return d }) } 
Enter fullscreen mode Exit fullscreen mode

You can take multiple approaches, but I'm just going to talk about the most simple one – building your own Promise using the constructor function and returning it. Let's try to modify the getValue function using Promises.

function getValue() {     return new Promise(resolve => {         setTimeout(() => {             resolve(42);         }, 5000);     }) } 
Enter fullscreen mode Exit fullscreen mode

A Promise constructor, if you recall, takes a callback function as its only parameter, which in turn takes in two callbacks, resolve and reject, which determine if the promise was fulfilled or rejected, accordingly. If you wanted, you could modify the code above to include a rejection criterion:

function getValue() {     return new Promise((resolve, reject) => {         setTimeout(() => {         if(Math.random() > 0.5)             resolve(42);         else             reject(-1);         }, 5000);     }) } 
Enter fullscreen mode Exit fullscreen mode

A Promise is an object that will hold a value in the future.

And now that the function works this way, you can easily call it with an async/await combo to make it look like it was synchronous. (The await keyword pauses the program execution until the Promise it's acting upon is settled)

(async function () {     try {         // promise resolution         let meaningOfLife = await getValue();         console.log(meaningOfLife);     }     catch (e) {         // promise rejection         console.error(e);     } })(); 
Enter fullscreen mode Exit fullscreen mode

I've wrapped it in an immediately-invoked function expression (IIFE), but you could easily do it with a regular async function.

Hope that helped!

[Photo by Adi K from Pexels]

javascriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.