zoukankan      html  css  js  c++  java
  • promise注意事项

    1.promise本身是同步的,只有.then .catch是异步的 所以使用时记得把它封装到一个函数里

    2.promise 有 3 种状态:pending、fulfilled 或 rejected。状态改变只能是 pending->fulfilled 或者 pending->rejected,状态一旦改变则不能再变。

    const promise = new Promise((resolve, reject) => {
      resolve('success1')
      reject('error')
      resolve('success2')
    })
     
    promise
      .then((res) => {
        console.log('then: ', res)
      })
      .catch((err) => {
        console.log('catch: ', err)
      })
    //结果为then:success1

    3.promise 可以链式调用。promise 每次调用 .then 或者 .catch 都会返回一个新的 promise,从而实现了链式调用。

    Promise.resolve(1)
      .then((res) => {
        console.log(res)
        return 2
      })
      .catch((err) => {
        return 3
      })
      .then((res) => {
        console.log(res)
      })
    //结果为1 2

    4..then 或者 .catch 中 return 一个 error 对象并不会抛出错误,所以不会被后续的 .catch 捕获,需要改成其中一种:

    return Promise.reject(new Error('error!!!'))
    throw new Error('error!!!')

    5.then 或 .catch 返回的值不能是 promise 本身,否则会造成死循环。类似于:

    process.nextTick(function tick () {
      console.log('tick')
      process.nextTick(tick)
    })

    6..then 或者 .catch 的参数期望是函数,传入非函数则会发生值穿透。

    Promise.resolve(1)
      .then(2)
      .then(Promise.resolve(3))
      .then(console.log)
    //结果为1
  • 相关阅读:
    django ORM
    django扩展知识
    django视图层
    php常用四种算法
    文件操作函数
    PHP开发中数组操作大全
    php 字符 常用函数
    MySQL的WHERE语句中BETWEEN与IN的用法和他们的区别
    $_SERVER
    PHP魔术方法和魔术常量
  • 原文地址:https://www.cnblogs.com/jiangxiaoming/p/13620731.html
Copyright © 2011-2022 走看看