Vithal Reddy
Vithal Reddy

Reputation: 442

Any way to use await in Normal function?

Is it possible to use await inside a normal function?

For Example:

function myFunction(v1, v2) {
    let v3 = await some db operation; returns a array
    console.log(v3);
    //do something
};

Upvotes: 4

Views: 16182

Answers (3)

fadedbee
fadedbee

Reputation: 44739

Yes, all async code is called from a normal function somewhere, but no you can't use the await keyword in a non-async function.

Async functions look like promises when inside non-async functions.

function myOuterFunction(v1, v2) {
    myFunction(v1, v2)
      .then(console.log)
      .catch(console.error);
}

async function myFunction(v1, v2) {
    let v3 = await some db operation; returns an array
    console.log(v3);
    //do something
};

(This example uses the functions console.log and console.error to handle returned values and exceptions.)

Upvotes: 7

Madara's Ghost
Madara's Ghost

Reputation: 174947

No, and for a good reason.

Before async functions were introduced: the following was entirely possible:

function foo() {
  var await = 42;
  var result = await + 42;
}

If they had made it so await was available in normal functions, that code would have been retroactively broken, causing what's called a backwards compatibility break.

This is also why yield is only available within function*.

Upvotes: 7

Niklas Higi
Niklas Higi

Reputation: 2309

No. The "magic" of asynchronous programming – that, in JavaScript, includes the usage of await – is that it doesn't block the execution of other code. If you want to use it, you have to adapt your codebase to use async functions where it makes sense.

If you really need to wait for asynchronous actions to complete inside normal synchronous functions, you could check whether the library you're using also offers sync functions (fs-extra for example does). But please, unless there's a really good reason not to, make your code asynchronous.

Upvotes: 4

Related Questions