544 Promise.allSettled,可选链操作符 --> ?.

Promise.allSettled

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Promise.allSettled</title>
</head>

<body>
  <script>
    // 声明两个promise对象
    const p1 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('商品数据 - 1')
      }, 1000)
    })

    const p2 = new Promise((resolve, reject) => {
      setTimeout(() => {
        // resolve('商品数据 - 2')
        reject('出错啦!')
      }, 1000)
    })

    // Promise.allsettled:始终返回成功的promise,包括参数中的每个promise实例的状态、值,即得到每一个异步任务的结果
    const result = Promise.allSettled([p1, p2])
    console.log(result)

    result.then(res => {
      res.forEach(item => {
        // 这样才能拿到 allsettled 中的数据
        console.log(item.status)
        console.log(item.value)
      })
    }).catch(rej =>
      console.log(rej)
    )


    const res = Promise.all([p1, p2])
    console.log(res)
    res.then(res => {
      res.forEach(item => {
        console.log(item)
      })
    }).catch(rej =>
      console.log(rej)
    )

  </script>
</body>

</html>

可选链操作符 --> ?.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>可选链操作符</title>
</head>

<body>
  <script>
    // ?.
    function main(config) {
      // const dbHost = config && config.db && config.db.host;
      const dbHost = config?.db?.host;
      console.log(dbHost);
    }

    main({
      db: {
        host: '192.168.1.100',
        username: 'root'
      },
      cache: {
        host: '192.168.1.200',
        username: 'admin'
      }
    })
  </script>
</body>

</html>
原文地址:https://www.cnblogs.com/jianjie/p/13680215.html