Home > Blockchain >  Does awaiting a non-Promise have any effect on performance?
Does awaiting a non-Promise have any effect on performance?

Time:07-18

Lets say I have this function

function sendMessage(message, content) {
  return message.send(content);
}

message returns a promise, but I don't actually need to resolve the promise as I don't care for the returned value.

In another async function, I call sendMessage as follows:

await sendMessage(message, 'Hello')

vs

return sendMessage(message, 'Hello')

The async function which am I calling this in is being awaited at the top level.

My question is what is the difference between me await vs returning, as the sendMessage function is not async and I don't need the returned value. What would be faster in terms of a more efficient for performance and event loop speed, if at all there even is a difference? Thanks!

CodePudding user response:

There isn't a performance difference between the two; If you don't need use the value of the resolved promise, you shouldn't be using return or await.

CodePudding user response:

As mozilla official docs mentioned:

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

The body of an async function can be thought of as being split by zero or more await expressions. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously.

On the other word, we usually use async functions and await keyword mostly to avoid promise chaining (promise.then() multiple times, which make our code really messy and unreadable) when running multiple promises synchronously. Since your code contained only one promise only, basicly await-ing the promise to fullfil or return it directly will be the same.

CodePudding user response:

async/await just is syntactic sugar,await need use with async otherwise it will throw a error,and it will transform it to a promise,promise are async non-promise are sync,it will affect thread execute order.

  • Related