Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling async function inside non-async function in React-Native - Firebase

This is what I'm trying do in React-Native. Async functions are making calls to firebase.

async functionOne() {
    asyncStuffHappens
}

functionTwo() {
    this.functionOne();
}

this.functionOne(); is undefined. I'm not sure how to call an async function from another function.

like image 733
wvicioso Avatar asked Mar 22 '17 00:03

wvicioso


People also ask

How do you call async function inside non async function?

Just treat async call as promise and attach . then to it: async function wait() { await new Promise(resolve => setTimeout(resolve, 1000)); return 10; } function f() { // shows 10 after 1 second wait().

Can you await inside a non async function?

You can not use the await keyword in a regular, non-async function. JavaScript engine will throw a syntax error if you try doing so.

How do you use async await inside function?

async and await 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.

What happens when you call async method without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.


1 Answers

Like this:

async functionOne() {
    asyncStuffHappens
}

functionTwo() {
    (async () => {
        await this.functionOne();
    })();
}

This is called an IIFE (Immediately-invoked function expression). It's a function executed right after it's created

like image 75
Vincent D'amour Avatar answered Sep 19 '22 02:09

Vincent D'amour