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

前端 未结 3 797
轮回少年
轮回少年 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题