shamgar
shamgar

Reputation: 120

Awaiting to a normal function

Is it possible await to a function that is not a promise? Maybe a function that cannot fail.

for example:

async function doWork() {
    const newData = await cannotFail();
    console.log("done: "+ newData);
}

function cannotFail() {
  var data = //cannot fail code . . .
    return data;
}

doWork();

I was thinking maybe with another syntax this option makes sense.

Upvotes: 2

Views: 2055

Answers (3)

code_monk
code_monk

Reputation: 10120

It's not necessary, but it is possible:

const newData = await Promise.resolve( cannotFail() );

Upvotes: 0

trincot
trincot

Reputation: 349956

It is possible to use await with an expression that does not evaluate to a promise. Whether that is useful, is questionable.

First of all, when await is followed by an expression that does not evaluate to a promise object, it is turned into one -- a resolved promise.

The main difference you get by using await with a non-promise or a resolved promise, is that await will make the async function return. This behaviour is not dependent on whether the promise is already resolved or not. await always postpones the further execution of the function by placing that resuming-job on the promise job queue.

See the difference here:

async function test() {
    let a = 1; // Without await
    console.log(a);
    return 2;
}

test().then(console.log);
console.log("end of main, synchronous code");

And with await

async function test() {
    let a = await 1; // With await
    console.log(a);
    return 2;
}

test().then(console.log);
console.log("end of main, synchronous code");

Note the different order of execution.

Upvotes: 1

Marko Borković
Marko Borković

Reputation: 1912

Consider these two examples

async function getData(){
  return "some data";
}

async function doSomething() {
  const data = await getData();
  console.log(data);
}

doSomething()

function getData(){
  return "some data";
}

async function doSomething(){
  const data = getData();
  console.log(data);
}

doSomething();

The result is exactly the same. You only use await when you want to wait for an asnyc function like it is synchronous. Normal functions already are synchronous.

And yes it is possible to use await on a normal function

function getData(){
  return 'some data';
}

async function doSomething(){
  const data = await getData();
  console.log(data);
 }
 
 doSomething();

There is just no reason to.

Upvotes: 5

Related Questions