Detailed explanation of js Promise and async/await usage

This article has participated in the "Newcomer Creation Ceremony" event to start the road of gold creation together.

foreword

In today's era of front-end and back-end separation, asynchrony is particularly important, and promises and async/await used to solve asynchronous problems have also become very important in es6. This article mainly introduces their usage, which is very simple and easy to remember.

asynchronous

    let a = 0

    setTimeout(() => {
      a = 1
    }, 1000)
    
    console.log(a) // 0
复制代码

At this point, the delay is executed asynchronously, and the value of a has not changed to 1 before it is used for output, and we can only get 0.

Promise

Sometimes we have to do asynchronous operations, like requesting data from the background, and we need time, waiting for it to get the data before using it.

That is, we want asynchronous content to be similar to synchronous.

Promise is an asynchronous solution that appeared in es6.

Basic use of Promise

  1. A function is received in new Promise(), and the input parameter is resolve,reject

  2. The function in the Promise can be executed for any length of time, until it is called resolve()or reject(). We put it here to execute after a delay of 1s. At this time, a has been assigned to 1, so the assigned a can be obtained.

  3. resolve()Entering .then is to execute the successful callback, and reject()entering .catch is to manually execute the error and enter the catch exception, which reject()is used less.

    let a = 0

    new Promise((resolve, reject) => {
      setTimeout(() => {
        a = 1
        resolve()
      }, 1000)
    })
      .then(() => {
        console.log(a) //1
      })
      .catch(() => {})
复制代码

Promise callback can accept input parameters

  1. .thenThe callback function in can have input parameters, and the input parameters are resolve()manually passed in, where res is the incoming a value.
  2. .catchThe relationship with reject()and is the same as the above two, but it becomes a callback when manually catching errors .
    let a = 0

    new Promise((resolve, reject) => {
      setTimeout(() => {
        a = 1
        resolve(a)
      }, 1000)
    })
      .then((res) => {
        console.log(res) //1
      })
      .catch(() => {})
复制代码

Promises can have continuous callbacks

  1. In the first way, the callback function accepts and returns a new Promise for the next callback.

  2. The second way is equivalent to new Promise and resolve(res)Promise.resolve(res) when res is normal data

  3. 第三种也是最常用的,再异步回调中直接返回普通数据也可当作接受了一个新的Promise进行下一步回调

    let a = 0

    new Promise((resolve, reject) => {
      setTimeout(() => {
        a = 1
        resolve(a)
      }, 1000)
    })
      .then((res) => {
        return new Promise((resolve, reject) => {
          resolve(res)
        })
        //等同于
        //return Promise.resolve(res)
        //等同于
        //return res
      })
      .then((res) => {
        console.log(res) //1
      })
      .catch(() => {})
复制代码

async/await

Promise的回调是可以帮我们解决了异步数据延迟的问题,但是当回调次数过多时,代码将会变得不优雅且异常难以理解,这就是回调地狱问题。

因此es7出现了async/await,用于解决回调地狱问题。

async/await有一个限制就是必须在函数中使用,因此我们将代码包进一个函数,并在函数前加上async,这样我们便可以在函数中使用await关键字

    const test = async () => {
      let a = 0
      ...
    }
    
    test()
复制代码

await用在哪里呢?用在.then回调前的Promise

await后面跟着Promise,而它的返回值便是回调时resolve()传来的值,代替了回调函数,看起来代码一下子就清晰很多了。

    const test = async () => {
      let a = 0

      const res = await new Promise((resolve, reject) => {
        setTimeout(() => {
          a = 1
          resolve(a)
        }, 1000)
      })

      console.log(res) //1
    }
    
    test()
复制代码

常见异步请求方法与Promise、async/await的关系

常见异步请求方法有:fetch、jq的ajax、axios等

fetch就是基于Promise设计的,回调的形式进行请求,所以也可以结合async/await非常方便的使用,想要了解的话,详见:js fetch异步请求使用详解

jq的ajax和axios也是同理,存在回调基本都是基于Promise的,我们只要将.then之前的部分看作Promise放在await后面,用一个变量接收回调结束返回的数据即可。

尾言

如果觉得这篇文章对你有帮助的话,欢迎点赞收藏哦,有什么错误或者意见建议也可以留言,感谢~

Guess you like

Origin juejin.im/post/7078882164032421924