Javascript Await/Async Feature - What if you do no

2019-03-04 07:00发布

I am learning about Javascript ES2017 async/await feature. Been reading a lot about it, and came across an understanding that await is like yield, and allows us to wait for the promises to complete.

From https://javascript.info/async-await

async function showAvatar() {

  // read our JSON
  let response = await fetch('/article/promise-chaining/user.json');
  let user = await response.json();

  // read github user
  let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
  let githubUser = await githubResponse.json();

  // show the avatar
  let img = document.createElement('img');
  img.src = githubUser.avatar_url;
  img.className = "promise-avatar-example";
  document.body.append(img);

  // wait 3 seconds
  await new Promise((resolve, reject) => setTimeout(resolve, 3000));

  img.remove();

  return githubUser;
}

showAvatar();

The question I have is, can I add await to every single line of code? Or what happens if I remove the word await?

And another question is, if async/ await makes the code seems to run synchronously and in order, why don't we don't use it at all (means make everything stay synchronous in the first place?)

Thank you!

3条回答
Animai°情兽
2楼-- · 2019-03-04 07:17

async functions are just syntactic sugar around Promises. It does nothing to change the function to be synchronous. In fact any function that is async implicitly returns a Promise object.

All await does is provide a convenient way to wait for a Promise. If you remove the await keyword, then the Promise will not be "unwrapped," which is not what you want if your function is going to operate on the result of that Promise.

To illustrate, this is the desugared version of your async function:

function showAvatar() {

  let githubUser;

  // read our JSON
  return fetch('/article/promise-chaining/user.json').then(response => {
    return response.json();
  }).then(user => {
    // read github user
    return fetch(`https://api.github.com/users/${user.name}`);
  }).then(githubResponse => {
    return githubResponse.json();
  }).then(user => {
    githubUser = user;

    // show the avatar
    let img = document.createElement('img');
    img.src = githubUser.avatar_url;
    img.className = "promise-avatar-example";
    document.body.append(img);

    // wait 3 seconds
    return new Promise((resolve, reject) => setTimeout(resolve, 3000));
  }).then(() => {
    img.remove();

    return githubUser;
  });
}

So await essentially just adds a .then callback to a Promise. Without await being specified, you'll just have a Promise object, not the result of the Promise.

查看更多
Rolldiameter
3楼-- · 2019-03-04 07:18

await tells the runtime to wait for the promise returned from the expression on the right-hand side to be fulfilled.

In the following code control is stopped in the async function until the promise returned by the fetch invocation is fulfilled, and the response value sent to the fulfilled promise is printed to the console.

async function go() {
  let response = await fetch('http://www.example.com');
  console.log(response); // print the response after some time
}
go();

If the await keyword was omitted then control would immediately continue to the next line of the function and the the promise returned by fetch would be immediately printed to the console.

async function go() {
  let response = fetch('http://www.example.com');
  console.log(response); // print the promise from fetch immediately
}
go();

await is a contextual keyword that only means something special when used inside a function marked async. By marking a function async you are telling the runtime to:

  1. treat the function as a generator function
  2. yield a value where the user types await (usually a promise)
  3. wrap the function in special handling logic so that progress through the function only occurs when each promise yielded by await is fulfilled

In this way, asynchronous control flows can be written in a style closer to the traditional synchronous style. ie. without nesting, callbacks or visible promises. try..catch can also be used in the normal way.

As another answer mentions, async, and await are syntactic sugar that ask the runtime to use existing objects (generator functions and Promises) behind the scenes to make async code easier to read and write.

can you await every line

I would guess you can. If the expression on the right of the await results in a promise, then the async/await behaviour detailed above occurs.

If the expression on the right of the await does not result in a promise, then I would guess the value is wrapped in a resolved promise for you, and logic continues per the above, as though the value came from an immediately resolved promise. This is a guess.

查看更多
地球回转人心会变
4楼-- · 2019-03-04 07:38

First, async / await, work with promises. If you are not calling from an async function or the await sentence is not then compatible, it won't work. In most cases if you remove await, you are going to end with a Promise and not the value of the promise.

Secondly, there are some cases that you may want to continue with the execution of the code while you are resolving some asynchronous task.

查看更多
登录 后发表回答