Home > Web Front-end > JS Tutorial > body text

The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise

青灯夜游
Release: 2018-09-12 16:45:32
Original
1564 people have browsed it

This chapter will introduce to you the difference between Async/Await and Promise in js asynchronous callback, and 6 reasons why Async/Await replaces Promise. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is Async/Await?

async/await is a new way of writing asynchronous code. The previous methods were callback functions and Promise.

async/await is implemented based on Promise and cannot be used for ordinary callback functions.

async/await, like Promise, is non-blocking.

async/await makes asynchronous code look like synchronous code, which is its magic.

Async/Await syntax

In the example, the getJSON function returns a promise, which will return a JSON object when the promise is successfully resolved. We just call this function, print the returned JSON object, and return "done".

Using Promise is like this:

const makeRequest = () =>
  getJSON()
    .then(data => {
      console.log(data)
      return "done"
    })makeRequest()
Copy after login

Using Async/Await is like this:

const makeRequest = async () => {
  console.log(await getJSON())
  return "done"}makeRequest()
Copy after login

They have some slight differences:

There are more functions in front An aync keyword. The await keyword can only be used within functions defined by aync. The async function will implicitly return a promise, and the resolve value of the promise is the value of the function return. (The reosolve value in the example is the string "done")

Point 1 implies that we cannot use await in the outermost code because it is not within the async function.

// 不能在最外层代码中使用
awaitawait makeRequest()
// 这是会出事情的 
makeRequest().then((result) => {
  // 代码
 })
Copy after login

await getJSON() means that console.log will wait until the promise of getJSON is successfully resolved before executing it.

Why Async/Await is better?

1. Simplicity

As can be seen from the example, using Async/Await obviously saves a lot of code. We don't need to write .then, we don't need to write anonymous functions to handle the resolve value of Promise, we don't need to define redundant data variables, and we avoid nested code. These small advantages add up quickly, as will become more apparent in the code examples that follow.

2. Error handling

Async/Await allows try/catch to handle both synchronous and asynchronous errors. In the promise example below, try/catch cannot handle the JSON.parse error because it is inside the Promise. We need to use .catch so that the error handling code is very redundant. Moreover, our actual production code will be more complicated.

const makeRequest = () => {
  try {
    getJSON()
      .then(result => {
        // JSON.parse可能会出错
        const data = JSON.parse(result)
        console.log(data)
      })
      // 取消注释,处理异步代码的错误
      // .catch((err) => {
      //   console.log(err)
      // })
  } catch (err) {
    console.log(err)
  }}
Copy after login

If aync/await is used, catch can handle JSON.parse errors:

const makeRequest = async () => {
  try {
    // this parse may fail
    const data = JSON.parse(await getJSON())
    console.log(data)
  } catch (err) {
    console.log(err)
  }}
Copy after login

3. Conditional statement

In the following example, data needs to be obtained and then returned based on the data Decide whether to return directly or continue to obtain more data. ·

const makeRequest = () => {
  return getJSON()
    .then(data => {
      if (data.needsAnotherRequest) {
        return makeAnotherRequest(data)
          .then(moreData => {
            console.log(moreData)
            return moreData          })
      } else {
        console.log(data)
        return data      }
    })}
Copy after login

These codes give me a headache just looking at them. It's easy to get confused with nesting (6 levels), parentheses, and return statements that just need to pass the final result to the outermost Promise.

Writing the above code using async/await can greatly improve readability:

const makeRequest = async () => {
  const data = await getJSON()
  if (data.needsAnotherRequest) {
    const moreData = await makeAnotherRequest(data);
    console.log(moreData)
    return moreData  } else {
    console.log(data)
    return data    
  }}
Copy after login

4. Intermediate value

You have probably encountered such a scenario, calling promise1, use the result returned by promise1 to call promise2, and then use the results of both to call promise3. Your code is likely to look like this:

const makeRequest = () => {
  return promise1()
    .then(value1 => {
      return promise2(value1)
        .then(value2 => {        
          return promise3(value1, value2)
        })
    })}
Copy after login

If promise3 does not require value1, you can simply nest the promise flat. If you can't stand nesting, you can put value 1 & 2 into Promise.all to avoid deep nesting:

const makeRequest = () => {
  return promise1()
    .then(value1 => {
      return Promise.all([value1, promise2(value1)])
    })
    .then(([value1, value2]) => {      
      return promise3(value1, value2)
    })}
Copy after login

This method sacrifices semantics for readability. There is no reason to put value1 and value2 in an array other than to avoid nesting.

If you use async/await, the code will become extremely simple and intuitive.

const makeRequest = async () => {
  const value1 = await promise1()
  const value2 = await promise2(value1)
  return promise3(value1, value2)}
Copy after login

5. Error stack

In the following example, multiple Promises are called. Assume that an error is thrown somewhere in the Promise chain:

const makeRequest = () => {
  return callAPromise()
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => callAPromise())
    .then(() => {
      throw new Error("oops");
    })}makeRequest()
  .catch(err => {
    console.log(err);
    // output
    // Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
  })
Copy after login

Return from the Promise chain The error stack gives no clue as to where the error occurred. Even worse, it's misleading; the only function in the error stack is called callAPromise, which has nothing to do with the error. (The file name and line number are still useful).

However, the error stack in async/await will point to the function where the error is located:

const makeRequest = async () => {
  await callAPromise()
  await callAPromise()
  await callAPromise()
  await callAPromise()
  await callAPromise()
  throw new Error("oops");}makeRequest()
  .catch(err => {
    console.log(err);
    // output
    // Error: oops at makeRequest (index.js:7:9)
  })
Copy after login

In a development environment, this advantage is not big. However, it will be very useful when you analyze the error log of the production environment. At this time, it is better to know that the error occurred in makeRequest than to know that the error occurred in the then chain.

6. Debugging

The last and most important point is that async/await can make code debugging easier. 2 reasons why debugging Promises is a pain:

1) You cannot set breakpoints in arrow functions that return expressions

The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise

2) If you Set a breakpoint in the .then code block and use the Step Over shortcut key. The debugger will not jump to the next .then because it will only skip the asynchronous code.

When using await/async, you no longer need so many arrow functions, so you can skip await statements just like debugging synchronous code

The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise

Conclusion

Async/Await is one of the most revolutionary features added to JavaScript in recent years. It will make you realize how bad Promise syntax is, and provide an intuitive alternative.

concern

Maybe you have some reasonable doubts about Async/Await:
It makes asynchronous code less obvious: we are used to using callback functions or .then to identify asynchronous code, and it may take us several weeks to get used to the new flag. However, C# has had this feature for many years, and friends who are familiar with it should know that the temporary inconvenience is worth it.
Node 7 is not an LTS (long-term support release): however, Node 8 will be released next month, and migrating your code to the new version will be very simple.

The above is the detailed content of The difference between js asynchronous callback Async/Await and Promise, 6 reasons why Async/Await replaces Promise. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!