Javascript Await/Async Feature - What if you do not have the await word in the function?

前端 未结 3 795
轮回少年
轮回少年 2021-01-27 18:37

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

相关标签:
3条回答
  • 2021-01-27 18:59

    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.

    0 讨论(0)
  • 2021-01-27 19:06

    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.

    0 讨论(0)
  • 2021-01-27 19:19

    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.

    0 讨论(0)
提交回复
热议问题