-1

I am very confused about which if these three is correct.

A(){
Return promise
}
Async A(){
Return promise
}
Async A(){
Return await promise //this seems very wrong but still...
}

Which of these are correct JavaScript? And if more than one is correct, what is the best practice here, if any?

Zoidbergseasharp
  • 2,378
  • 1
  • 8
  • 14

2 Answers2

0

Async/await can be considered as syntax sugar for Promises. Any function that returns a Promise object can be used as an async function. The two styles (promise style vs. async/await style) can be mixed without issue.

function A() {
  return Promise.resolve('foo');
}

async function B() {
  var aResult = await A();

  return aResult;
}

B().then(console.log);

Best practice would be to pick one style and stick with it, for readability. Async/await is the newer style, and has the advantage that it avoids the .then pyramid of doom.

Note that async/await, or even promises, may not be supported in all runtimes and may require a transpiler (like babel).

Robert Stiffler
  • 585
  • 2
  • 9
0

You could use all of them as all three are valid. But given your examples, only the first makes sense.

Each of your examples returns a Promise. You can either use a().then(/*...*/) or await a() (only within an async function) to get their response when they resolve. Read more about Promise or async/await in general.


function a() {
  return Promise.resolve();
}

This is how you should write a function that returns a Promise.


async function a() {
  return Promise.resolve();
}

This works as well, but only functions that actually use the await keyword need to be annotated with async. Functions that just return a Promise without using await in their body do not need to be async.


Async A(){
Return await promise //this seems very wrong but still...
}

This is just an unncessary step. Read more here and here.

str
  • 38,402
  • 15
  • 99
  • 123