Home > Software engineering >  why is async keyword added in a node function while node is already asynchronous ? why we need to te
why is async keyword added in a node function while node is already asynchronous ? why we need to te

Time:12-22

I want to know actual meaning of async keyword usage before function name in node js.

CodePudding user response:

Node.js is asynchronous in the idea that code does not need to run in the order it was called. However, you have to tell Node to do that for you.

Defining a function as async means that the function will return a Promise that resolves to whatever the return of the function is:

// This function returns a `Promise` that resolves to `true`
const func = async () => {
  return true;
}

Importantly, defining a function as async also allows the use of the await keyword:

const func = async () => {
  const result = await fetch("someUrl");
  return await result.toJSON();
}

async/await is just syntactic sugar for traditional Promises:

// This is the same function as above
const func = () => {
  return fetch("someUrl")
    .then(result => result.toJSON())
}

CodePudding user response:

An async function will ALWAYS return a promise. If it returns a non-promise, the return value will be wrapped in Promise.resolve. If it throws, it will wrap the exception in Promise.reject.

So the async keyword is a contract that guarantees the return value of the function to be asynchronus.

And this is required for the await keyword, because you can only await if you return a promise.

  • Related