简体   繁体   中英

Should I define async function if I explicitly return a Promise?

We know that async functions return a Promise implicitly. But I have a purely pedantic question. Should I put an async keyword if I return a Promise explicitly?

Is this:

const wait = async ms => new Promise(
    resolve => setTimeout(resolve, ms)
);

Any different than this?

const wait = ms => new Promise(
    resolve => setTimeout(resolve, ms)
);

I believe that technically they are identical. Is there any style guide or official recommendation behind any of these two ways to define this kind of function?

There are three main reasons I think about for using async functions:

  1. You want to use await .
  2. You want it to automatically catch synchronous exceptions and turn them into a rejected promise.
  3. You want it to always return a promise, regardless of what your function actually returns.

So, if you aren't using await and you don't need point #2 and you are manually returning a promise already, then there's really no reason/advantage to declaring the function as async .


A few more thoughts on the three points above.

Point #1 requires async if you're going to use await . There is no other way around it.

Points #2 and #3 are really just programming conveniences. If you either catch your own synchronous exceptions or are sure there are no synchronous exceptions and you are controlling all code paths to return a promise, then async is not necessary.

Both points #2 and #3 can arise if your code has both a synchronous code path and an asynchronous code path, such as checking a cache and returning a value if its present in the cache and, if not in the cache, then make a network request to fetch the value. As described above, this can be coded manually without async , but the code can sometimes be a little simpler with async because it will automaticlly catch your synchronous exceptions and automatically wrap a return value in a promise.

if you use promise don't need yo use asycn Proime is already tells that its asycn but you need to use await front of it

for ex ;

const wait = await (ms) => new Promise(
    resolve => setTimeout(resolve, ms)
);

example for asycn;

const wait = await exFunction()

const exFunction = asycn () => {
// some stuff to do which has asycn operations
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM