promise 4个方法

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>promise</title>
</head>

<body>

</body>
<script>
  function asyncFun1() {
    return new Promise(function (resolve, reject) {
      setTimeout(() => {
        var num = Math.floor(Math.random() * 900 + 100);
        console.log("fun1num:",num)
        if (num > 500) {
          resolve({
            code: '1',
            num: num,
            from:'fun1'
          })
        } else {
          reject({
            code: 'error',
            num: -1,
            from:'fun1'
          })
        }
      }, 1500)
    })
  }
  function asyncFun2(num1) {
    return new Promise(function (resolve, reject) {
      setTimeout(() => {
        var num = Math.floor(Math.random() * 900 + 100);
        console.log("fun2num:",num)
        if (num > 500) {
          let total = num1 + num;
          console.log(num1)
          resolve({
            total:total
          })
        } else {
          reject({
            code: 'error',
            num: -1,
            from:'fun2'
          })
        }
      }, 1000)
    })
  }

  // 1. 串行
  // asyncFun1().then(res=>{
  //   console.log("第一个方法",res)
  //   return res.num
  // }).then(parmeFor1=>{
  //   console.log("第一个then的返回值",parmeFor1)
  //   return asyncFun2(parmeFor1)
  // }).then(res3=>{
  //   console.log("第三个then执行",res3)
  // }).catch(err=>{
  //   console.log("失败了",err)
  // })
 
 //2.并行 返回的是promise对象,返回状态有一个失败且都失败,
//  let p1 = asyncFun1();
//  let p2 = asyncFun2();
//  Promise.all([p1,p2]).then(res=>{
//    console.log(res)
//  }).catch(err=>{
//    console.log("err",err)
//  })

  //3. any 任何一个先resolve就resolve,全部是否就reject
//   Promise.any([asyncFun1(),asyncFun2()]).then(res=>{
//     console.log("any",res)
//   }).catch(err=>{
//    console.log("err",err)
//  })

   //4. race 看谁跑得快,就返回哪一个
//    Promise.race([asyncFun1(),asyncFun2()]).then(res=>{
//     console.log("race",res)
//   }).catch(err=>{
//    console.log("err",err)
//  })

   //5. allSettled 每一个异步任务都想得到结果就使用Promise.allSettled()
   Promise.allSettled([asyncFun1(),asyncFun2()]).then(res=>{
    console.log("allSettled",res)
  }).catch(err=>{
   console.log("err",err)
 })
</script>

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。