0

I understand that we use async when we want to use await inside a function, but if the function returns a promise (without awaiting it), should we prefix the name with async?

Example 1:

async function fetching() {
 return fetch('someUrl')
}

Example 2:

function fetching() {
  return fetch('someUrl');
}

What is more proper, example 1 or example 2?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

2 Answers2

0

async and await are just convenience methods to work with promises.

async function foo(){
    return true;
}

is exactly the same as

function bar(){
    return new Promise(resolve => {
        resolve(true);
    });
}

because async encapsulates the return value in a promise, which is resolved, when the method finishes.

In a similiar way

async function oof(){
    let myVal = await foo();
    do_something_else();
}

(Note: async only has to be used here to be able to use await)

is the same as

function rab(){
    let myVal;
    bar().then(val => myVal = val);
}

await just makes it easier to chain promises

Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
0

The result of an async function is automatically wrapped in Promise.resolve, this means that if you return a Promise, it will be unwrapped automatically. In essence, it does not matter.

const delay = x => new Promise(res => setTimeout(() => {
  console.log("Resolved");
  res();
}, x));

function fetch()
{
  return delay(1000);
}
async function fetchA()
{
  return delay(1000);
}

(async () =>
{
  console.log("Create fetch");
  const f1 = fetch();
  console.log("Await fetch");
  await f1;
  console.log("Awaited fetch");
  
  console.log("Create fetchA");
  const f2 = fetchA();
  console.log("Await fetchA");
  await f2;
  console.log("Awaited fetchA");
})();
H.B.
  • 166,899
  • 29
  • 327
  • 400