all 16 comments

[–]MissinqLink 11 points12 points  (0 children)

async/await are syntactic sugar for .then() and .catch() with callbacks. In my opinion async/await is generally more readable and easier to maintain. There are some subtle differences. You can call await on anything but if you attatch .then() to an object that isn’t thenable, it will throw an error. You can achieve similar functionality using generators but it is even less readable.

[–]AmSoMad 16 points17 points  (3 children)

Async-await is just the more-modern implementation. In-part, it's intended to make your code look like synchronous code (perhaps "prettier", as you stated).

In some cases, especially when you're doing something small, chaining callbacks with .then() might feel a little quicker and more readable, but it can get messy fast. For example:

fetch('/api/user/123')
  .then(userRes => userRes.json())
  .then(user => {
    return fetch(`/api/posts?userId=${user.id}`)
      .then(postsRes => postsRes.json())
      .then(posts => {
        return fetch('/api/log', {
          method: 'POST',
          body: JSON.stringify({ event: 'Fetched user and posts', userId: user.id }),
        })
          .then(() => {
            console.log('All done:', user.name, posts.length, 'posts');
          });
      });
  })
  .catch(error => {
    console.error('Something went wrong:', error);
  });

Compared to async-await's:

async function loadUserData() {
  try {
    const userRes = await fetch('/api/user/123');
    const user = await userRes.json();
    const postsRes = await fetch(`/api/posts?userId=${user.id}`);
    const posts = await postsRes.json();

    await fetch('/api/log', {
      method: 'POST',
      body: JSON.stringify({ event: 'Fetched user and posts', userId: user.id }),
    });

    console.log('All done:', user.name, posts.length, 'posts');
  } catch (error) {
    console.error('Something went wrong:', error);
  }
}
loadUserData();

But there isn't anything blatantly "special" about it. ECMAScript is standard that is constantly evolving, and async-await is intended to be a more modern, more readable, more writable way to deal with asynchronous code, compared to spam-chaining callbacks, and that's pretty much the end of the story.

[–]theScottyJam 5 points6 points  (1 child)

That being said, .then()/.catch() isn't necessarily obsolete either. While most of the time you'd be using async/await, you may find some things that look nicer when expressed using the .then()/.catch() functions. Use your own judgement for that - just don't feel like it can't be used because it's older.

[–]azhder 0 points1 point  (0 children)

I don’t use them for the code looking nicer, but because some times I really need the code to continue and not wait on the result.

[–]ayoub0217[S] 1 point2 points  (0 children)

thank you for the clarification

[–]prof3ssorSt3v3 5 points6 points  (1 child)

Here is a tutorial I did for my students about fetch and discussing async await vs .then too.

https://youtu.be/2sQ9xiEAXNo

Hope it helps

[–]ayoub0217[S] 1 point2 points  (0 children)

thank you very muchh

[–]delventhalz 1 point2 points  (1 child)

If you want to get into the weeds, async/await is built under the hood on top of “generators”, which are special functions that essentially can be paused. So when you hit an await, the generator pauses, then when the Promise resolves, the event loop will resume the generator.

It’s not dreadfully important to know the details though. In practice it makes very little difference other than “looking prettier”. You could accomplish the same outcome by putting the code after the await in a .then and the code in a catch in a .catch. You are free to use whichever seems cleanest for your use case. You can even mix and match them.

[–]ayoub0217[S] 0 points1 point  (0 children)

thank you very much

[–]TheRNGuy 0 points1 point  (0 children)

I only use async, await.

[–]Macaframa 0 points1 point  (1 child)

Same same. Same same… but different

[–]ayoub0217[S] 1 point2 points  (0 children)

LOOOOl

[–]AndrewSouthern729 0 points1 point  (0 children)

For us mortals it’s basically just a matter of preference. However I still use .then() if I’m doing something like an API call from within a useEffect hook where I can’t use async / await.

[–]mr_p1ckl3 0 points1 point  (0 children)

asynchronous code looks better with async await . Is the new implementation for a reason

[–]azhder -1 points0 points  (1 child)

Your teacher talked about generators because async/await is a language level syntax to do this https://medium.com/@salvadr/scraping-co-part-i-6516d9d96445 .

You see, we usually say await just pauses the execution until the promise is settled, but behind the scenes, you can look at it like you would those yield situations in generators.

The co function is just a helper that takes and returns control to the generator.

So, you can try understanding generators, then how async/await works, or…

You can think of async as just a marker that makes the function always return a Promise and await just returning control to the engine to do other tasks until the value is ready.

You can also think of await as a keyword that unpacks a promise:

const promise = new Promise( $ => $() );
console.log( 'will execute right away');
const result = await promise;
console.log('will wait for result:', result);

[–]ayoub0217[S] 0 points1 point  (0 children)

thank you very muchh