Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an asynchronous JavaScript function?

Can anyone please help me with the following, I am new to Async\Await in Javascript:

I have a trivial class:

function Thing()
{
}

Thing.prototype.ShowResult = function ()
{
    var result = this.GetAsync();

    alert(result);
}

Thing.prototype.GetAsync = async function ()
{
    var result = await this.AsyncFunc();

    return result;
}

Thing.prototype.AsyncFunc = async function ()
{
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(6);
        }, 2000);
    });
}

I call it like this:

var thing = new Thing();

thing.ShowResult();

I expected a delay of 2 seconds before seeing the result of 6.

Instead I immediately see:

[object Promise]

How can I correctly await the result? Thanks for any help.

like image 516
user3738290 Avatar asked Jul 13 '20 16:07

user3738290


People also ask

How do you call an asynchronous function?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

How do asynchronous functions work in JavaScript?

Asynchronous programming is a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result.

What are asynchronous functions in JavaScript?

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.

What is async async / await function in JavaScript?

Async / await function is a function declared using the “Async” keyword and “Await” keywords in the source code. Those functionalities enable the asynchronous, promise-based behavior to cleaner written styles as well. Note: Above basic syntax shows how to place function names and variables as mentioned as keywords.

What happens when you put async before a function?

Putting the async keyword before a function makes it an asynchronous function. This basically does 2 things to the function: If a function doesn't return a promise the JS engine will wrap this value into a resolved promise. Thus, the function will always return a promise.

Are callbacks asynchronous in JS?

Callbacks are asynchronous in JS. stackoverflow.com/a/36213995/2963111 - "In Javascript, on the other hand, callbacks are usually asynchronous - you pass a function that will be invoked ... but other events will continue to be processed until the callback is invoked."


2 Answers

You have to make the parent function consuming the async function async as well.

function Thing() {}

Thing.prototype.ShowResult = async function() { // add async
  var result = await this.GetAsync(); // await the response

  alert(result);
}

Thing.prototype.GetAsync = async function() {
  var result = await this.AsyncFunc();

  return result;
}

Thing.prototype.AsyncFunc = async function() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(6);
    }, 2000);
  });
}

Then you can call ShowResult

var thing = new Thing();

await thing.ShowResult();

But, if you're calling thing.ShowResult outside of an async function you'll have to use the Promise syntax since you can't await something that isn't in an async function. There's no concept of a "top level await" in JS. Yet.

var thing = new Thing();

thing.ShowResult().then( result => console.log(result) );
like image 93
mwilson Avatar answered Sep 29 '22 22:09

mwilson


In JavaScript, async functions always return a Promise (this is why you see [object Promise]), which can be resolved either by calling its then method or by using the await keyword. For now, await can only be used inside async functions.

To apply this to your problem, you can do one of the following:

#1

Thing.prototype.ShowResult = function ()
{
    this.GetAsync().then(alert);
}

thing.ShowResult();

#2

In this approach, ShowResult is also an async function. So what I wrote above also applies to it.

Thing.prototype.ShowResult = async function ()
{
    var result = await this.GetAsync();
}

await thing.ShowResult();
like image 35
Befeepilf Avatar answered Sep 29 '22 22:09

Befeepilf