Promise

Magicsoftware 2020-03-08

Promise

 promise的基本使用

<!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>Document</title>
</head>
<body>
  <script>
    new Promise((resolve,reject)=>{
      setTimeout(()=>{
        resolve("abc")
        reject("sssss")
      },1000)
    }).then(data=>{
      console.log(data);
      //第一次
      return new Promise((resolve,reject)=>{
        setTimeout(()=>{
         resolve("sss")
        },1000)
      }).then(data=>{
        console.log(data)
     //第二次
      return new Promise((resolve,reject)=>{
        setTimeout(() => {
          resolve("ccc")
        }, 1000);
      }).then(data=>{
        console.log(data)
      },err=>{
        console.log(err)
      })  
      })//简写err
    })
    // }).catch(error=>{
    //   console.error(error);
    // })
  </script>
</body>
</html>

promise的简写

<!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>Document</title>
</head>
<body>
  <script>
    new Promise((resolve,reject)=>{
      setTimeout(()=>{
        resolve("abc")
        reject("asdasd")
      },1000)
    }).then(data=>{
      console.log(data);
      //第一次
       return data+"a"//最简便                      // return Promise.resolve(data+"a")   第二简便
    }).then(data=>{
        console.log(data)
     //第二次
      return  Promise.resolve("aad")
      }).then(data=>{
        console.log(data)
      }).catch(err=>{
        console.log(err)
      })  
  </script>
</body>
</html>

all的使用

<!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>Document</title>
</head>
<body>
  <script>
    Promise.all([
    new Promise((resolve,reject)=>{
      setTimeout(()=>{
         resolve([{age:18,name:"wang"},‘result1‘])
      },1000)
    }),
     
    new Promise((resolve,reject)=>{
      setTimeout(() => {
        resolve({age:17,name:"wangxingyu"},"result2")
      }, 1000);
      })
    ]).then(results=>{
      console.log(results);
    })
  </script>
</body>
</html>

相关推荐