ChatGPT解决这个技术问题 Extra ChatGPT

What is the difference between JavaScript promises and async await?

I have been using ECMAScript 6 and ECMAScript 7 features already (thanks to Babel) in my applications - both mobile and web.

The first step obviously was to ECMAScript 6 levels. I learnt many async patterns, the promises (which are really promising), generators (not sure why the * symbol), etc. Out of these, promises suited my purpose pretty well. And I have been using them in my applications quite a lot.

Here is an example/pseudocode of how I have implemented a basic promise-

var myPromise = new Promise(
    function (resolve,reject) {
      var x = MyDataStore(myObj);
      resolve(x);
    });

myPromise.then(
  function (x) {
    init(x);
});

As time passed, I came across ECMAScript 7 features, and one of them being ASYNC and AWAIT keywords/functions. These in conjunction do great wonders. I have started to replace some of my promises with async & await. They seem to add great value to programming style.

Again, here is a pseudocode of how my async, await function looks like-

async function myAsyncFunction (myObj) {
    var x = new MyDataStore(myObj);
    return await x.init();
}
var returnVal = await myAsyncFunction(obj);

Keeping the syntax errors (if any) aside, both of them do the exact same thing is what I feel. I have almost been able to replace most of my promises with async,awaits.

Why is async,await needed when promises do a similar job?

Does async,await solve a bigger problem? Or was it just a different solution to callback hell?

As I said earlier, I am able to use promises and async,await to solve the same problem. Is there anything specific that async await solved?

Additional notes:

I have been using async,awaits and promises in my React projects and Node.js modules extensively. React especially have been an early bird and adopted a lot of ECMAScript 6 and ECMAScript 7 features.

Your first code block appears to use a promise for a synchronous operation. Why would you do that? Synchronous is, by nature, easier to write code for so there should be little reason to wrap a synchronous operation into a promise and force it to now be async.
@jfriend00 Yes you are right. Edited the code. Thanks.
Your still trying to use async tools with synchronous functions - now in both code blocks. Why?
@jfriend00 Ok. Here I have my code gist.github.com/bozzmob/26d38b83dc37d1be37f5 . Please can you tell me what am I doing wrong?
It sounds like you just need to do a bunch of reading to understand what async and await are for. Here are some articles: The long road to Async/Await in JavaScript and Simplifying Asynchronous Coding with ES7 Async Functions and Taming the asynchronous beast with ES7.

J
Josh Beam

Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem?

async/await simply gives you a synchronous feel to asynchronous code. It's a very elegant form of syntactical sugar.

For simple queries and data manipulation, Promises can be simple, but if you run into scenarios where there's complex data manipulation and whatnot involved, it's easier to understand what's going on if the code simply looks as though it's synchronous (to put it another way, syntax in and of itself is a form of "incidental complexity" that async/await can get around).

If you're interested to know, you can use a library like co (alongside generators) to give the same sort of feel. Things like this have been developed to solve the problem that async/await ultimately solves (natively).


Please can you elaborate on what "incidental complexity" mean? Also, when it comes to performance, there is no difference between the two?
@bozzmob, shaffner.us/cs/papers/tarpit.pdf <-- he explains "incidental complexity" in there. As far as your performance question, I doubt it, especially with the V8 engine being what it is. I'm sure there are some perf tests out there, but I wouldn't worry about that too much. Don't waste your time on micro-optimization when it's not necessary.
Thanks a lot! This is some great information that I have got from you. And yes, will not look into micro optimizations.
I found this explanation helpful nikgrozev.com/2015/07/14/…
S
Stephen Cleary

Async/Await provide a much nicer syntax in more complex scenarios. In particular, anything dealing with loops or certain other constructs like try/catch.

For example:

while (!value) {
  const intermediate = await operation1();
  value = await operation2(intermediate);
}

This example would be considerably more convoluted just using Promises.


This is a great example to understand the same. So, when it comes to performance, there is no difference between the two? And which is a better to use in code? Async Await seems better after seeing your example atleast.
@bozzmob: There's no difference in performance. If you're comfortable using async/await, then I would recommend it. I don't use it myself yet because it's not actually part of the official standard.
Yes, I agree its not a part of the standard, but, in case of ReactJS(react native specifically), I am kinda forced to use it at some parts of the code. So, half of them are promises and half are async-awaits. So, I asked you those questions. Thanks for the needy information.
I think a lot of people are confused and/or misled when no one uses the try/catch block in their code samples.
You mean like that ? const getValue = value => value || operation1().then(operation2).then(getValue);
P
Peter Mortensen

Why is async,await needed when Promises does similar job? Does async,await solve a bigger problem? or was it just a different solution to callback hell? As I said earlier, I am able to use Promises and Async,Await to solve the same problem. Is there anything specific that Async Await solved?

The first things you have to understand that async/await syntax is just syntactic sugar which is meant to augment promises. In fact the return value of an async function is a promise. async/await syntax gives us the possibility of writing asynchronous in a synchronous manner. Here is an example:

Promise chaining:

function logFetch(url) {
  return fetch(url)
    .then(response => response.text())
    .then(text => {
      console.log(text);
    }).catch(err => {
      console.error('fetch failed', err);
    });
}

Async function:

async function logFetch(url) {
  try {
    const response = await fetch(url);
    console.log(await response.text());
  }
  catch (err) {
    console.log('fetch failed', err);
  }
}

In the above example the await waits for the promise (fetch(url)) to be either resolved or rejected. If the promise is resolved the value is stored in the response variable, and if the promise is rejected it would throw an error and thus enter the catch block.

We can already see that using async/await might be more readable than promise chaining. This is especially true when the amount of promises which we are using increases. Both Promise chaining and async/await solve the problem of callback hell and which method you choose is matter of personal preference.


P
Peter Mortensen

Async/await can help make your code cleaner and more readable in cases where you need complicated control flow. It also produces more debug-friendly code. And makes it possible to handle both synchronous and asynchronous errors with just try/catch.

I recently wrote this post showing the advantages of async/await over promises in some common use cases with code examples: 6 Reasons Why JavaScript Async/Await Blows Promises Away (Tutorial)


R
Ran Turner

await/async are often referred to as syntactic sugar to promises and let us wait for something (e.g. an API call), giving us the illusion that it is synchronous in an actual asynchronous code, which is a great benefit.

The things you want to achieve with async/await is possible with promises (but without the advantages of async/await). Lets take an example with this code:

const makeRequest = () => //promise way
  getJSON()
    .then(data => {
      return data
    })

makeRequest();

const makeRequest = async () => { //async await way
  const data = await getJSON();
  return data;
 }

makeRequest()

Why is async/await prefered over promises?

Concise and clean - We don’t have to write .then and create an anonymous function to handle the response, or give a name data to a variable that we don’t need to use. We also avoided nesting our code. async/await is a lot cleaner. Error handling - Async/await makes it finally possible to handle both synchronous and asynchronous errors with the same try/catch format. Debugging - A really good advantage when using async/await is that it’s much easier to debug than promises for 2 reasons: 1) you can’t set breakpoints in arrow functions that return expressions (no body). 2) if you set a breakpoint inside a .then block and use debug shortcuts like step-over, the debugger will not move to the following .then because it only “steps” through synchronous code. Error stacks - The error stack returned from the promises chain gives us no idea of where the error occurred and can be misleading. async/await gives us the error stack from async/await points to the function that contains the error which is a really big advantage.


N
Nikola Pavicevic

Await syntax is simply synchronous code because you have to wait until the promise is fulfilled or rejected. Actually code execution after await keyword will be suspended until the promise resolve or reject.


The only thing this "new" answer does is to repeat what half of the other answers are already saying, including the accepted answer.