久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

ES6 promise

 Coder編程 2020-08-15

回調(diào)與promise
方法 用于請(qǐng)求數(shù)據(jù)(模擬)
resolve代表成功時(shí)要做的事情

    function f() {
        return new Promise(resolve => {
            setTimeout(function() {
                resolve();
            }, 1000);
        })
    }

    f()
        .then(function() {
            console.log(1);
            //return promise實(shí)例,,才能繼續(xù).then()
            return f();
        })
        .then(function() {
            console.log(2);
            return f();
        })
        .then(function() {
            console.log(4);
            return f();
        })
        .then(function() {
            console.log(3);
            return f();
        })
        .then(function() {
            console.log(5);
            return f();
        })
        .then(function() {
            console.log(6);
        });

案例:
Promise 新建后立即執(zhí)行,所以首先輸出的是Promise,,然后,then方法指定的回調(diào)函數(shù),,將在當(dāng)前腳本所有同步任務(wù)執(zhí)行完才會(huì)執(zhí)行,,所以resolved最后輸出

    let promise=new Promise(resolve=>{
        console.log('Promise');
        resolve();
    });

    promise.then(function(){
        console.log('resolved');
    });

    console.log('Hello!');
    //結(jié)果:Promise Hello! resolved

Promise小動(dòng)畫案例:
index.html

<!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>
  <style>
    #el {
      width: 100px;
      background: green;
      transition: all 1s;
      color: white;
      line-height: 100px;
      text-align: center;
      font-size: 40px;
    }
  </style>
</head>
<body>
  <div id="el"></div>
  <button id="btn">開始</button>
  <script src="./main.js"></script>
</body>
</html>

main.js

function moveTo(el, x, y) {
    return new Promise(resolve => {
        el.style.transform = `translate(${x}px, ${y}px)`;
        setTimeout(function() {
            resolve();
        }, 1000);
    });
}

let el = document.querySelector('div');

document.querySelector('button').addEventListener('click', e => {
    moveTo(el, 100, 100)
        .then(function() {
            console.log('第一次移動(dòng)');
            return moveTo(el, 200, 200);
        })
        .then(function() {
            console.log('第二次移動(dòng)');
        })
        .then(function() {
            console.log('第二次移動(dòng)');
        });
});

錯(cuò)誤處理
resolve成功時(shí)操作
reject失敗時(shí)操作

  function f(val) {
    return new Promise((resolve, reject) => {
      if (val) {
        resolve({ name: '小明' });
      } else {
        reject('404');
      }
    }); 
  }

  f(true)
    .then((data) => {
      console.log(data)
    }, e => {
      console.log(e);
    })

catch
使用實(shí)例的catch方法 可以捕獲錯(cuò)誤

    f(true)
      .then(data => {
        console.log(data);
        return f(false);
      })
      .then(() => {
        console.log('我永遠(yuǎn)不會(huì)被輸出');
      })
      .then(() => {

      })
      .catch(e => {
        console.log(e);
        return f(false) ;
      });

finally
不論成功還是失敗 finally中的內(nèi)容一定會(huì)執(zhí)行

   f(true)
      .then(data => {
        console.log(data);
        return f(false);
      })
      .catch(e => {
        console.log(e);
        return f(false);
      })
      .finally(() => {
        console.log(100);
      });

promise三種狀態(tài)
pending 進(jìn)行中
fulfilled 成功
rejected 失敗
狀態(tài)的改變不可逆:
pending可以到fulfilled或者rejected


 

Promise.all方法可以把多個(gè)promise實(shí)例 包裝成一個(gè)新的promise實(shí)例
Promise.all([ promise1, promise2 ]) : Promise
模擬需要多個(gè)請(qǐng)求的數(shù)據(jù) 才能進(jìn)行下一步操作的情況

    function getData1() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第一條數(shù)據(jù)加載成功');
          resolve('data1');
        }, 1000);
      });
    }
    function getData2() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第二條數(shù)據(jù)加載成功');
          resolve('data2');
        }, 1000);
      });
    }
    function getData3() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第三條數(shù)據(jù)加載成功');
          resolve('data3');
        }, 1000);
      });
    }
    function getData4() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第四條數(shù)據(jù)加載成功');
          resolve('data4');
        }, 2000);
      });
    }
    // 所有數(shù)據(jù)都成功,則總決議成功,,并返回所有成功提示
    let p = Promise.all([getData1(),getData2(),getData3(),getData4()]);
    p.then(arr => {
      console.log(arr);
    });

一條數(shù)據(jù)失敗,,則總決議失敗,并返回錯(cuò)誤信息

    function getData1() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第一條數(shù)據(jù)加載成功');
          resolve('data1');
        }, 1000);
      });
    }
    function getData2() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第二條數(shù)據(jù)加載成功');
          resolve('data2');
        }, 1000);
      });
    }
    function getData3() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第三條數(shù)據(jù)加載成功');
          resolve('data3');
        }, 1000);
      });
    }
    function getData4() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject('data4 err');
        }, 500);
      });
    }
    // 一條數(shù)據(jù)失敗,,則總決議失敗,,并返回錯(cuò)誤信息
    let p = Promise.all([getData1(),getData2(),getData3(),getData4()]);
    p.then(arr => {
      console.log(arr);
    },e=>{
        console.log(e);
    });

空數(shù)組直接決議為成功

    function getData1() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第一條數(shù)據(jù)加載成功');
          resolve('data1');
        }, 1000);
      });
    }
    function getData2() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第二條數(shù)據(jù)加載成功');
          resolve('data2');
        }, 1000);
      });
    }
    function getData3() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('第三條數(shù)據(jù)加載成功');
          resolve('data3');
        }, 1000);
      });
    }
    function getData4() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject('data4 err');
        }, 500);
      });
    }
    // 空數(shù)組直接決議為成功
    let p = Promise.all([]);
    p.then(() => {
      console.log('null');
    },e=>{
        console.log(e);
    });

promise.race
只要有一個(gè)決議為成功或者失敗,就會(huì)返回

  function getData1() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('第一條數(shù)據(jù)加載成功');
        reject('err');
      }, 500);
    });
  }
  function getData2() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('第二條數(shù)據(jù)加載成功');
        resolve('data2');
      }, 1000);
    });
  }
  function getData3() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('第三條數(shù)據(jù)加載成功');
        resolve('data3');
      }, 1000);
    });
  }

  let p = Promise.race([getData1(),getData2(),getData3()]);

  p.then(data => {
      console.log(data);
  }, e => {
      console.log(e);
  })

空數(shù)組會(huì)被掛起

  let p = Promise.race([]);

Promise.resolve() 和 Promise.reject()
常用來生成已經(jīng)被決議為失敗或者成功的promise實(shí)例


 

Promise.resolve傳遞一個(gè)普通的值
決議成功并把值傳遞過去

    let p1 = new Promise(resolve => {
      resolve('成功!');
    });
    let p2 = Promise.resolve('成功!');

Promise.resolve傳遞一個(gè)promise實(shí)例

    let poruomiesi = new Promise(resolve => {
      resolve('耶!')
    });
    // 直接返回傳遞進(jìn)去的promise
    let p = Promise.resolve(poruomiesi);
    p.then(data => void console.log(data));
    console.log(p === poruomiesi); 

Promise.resolve傳遞一個(gè)thenable
如果傳遞的是個(gè)thenable

    let obj = {
      then(cb) {
        console.log('我被執(zhí)行了');
        cb('哼,!');
      },
      oth() {
        console.log('我被拋棄了');
      }
    }
    // 立即執(zhí)行then方法
    Promise.resolve(obj).then(data => {
      console.log(data);
    });

Promise.reject
直接決議為失敗,不做處理

    Promise.reject({ then() { console.log(1) } })
      .then(() => {
        console.log('我不會(huì)被執(zhí)行');
      }, e => {
        console.log(e);
      });

異步任務(wù)總是在同步任務(wù)之后執(zhí)行
把同步的任務(wù)轉(zhuǎn)成異步任務(wù)

    function createAsyncTask(syncTask) {
      return Promise.resolve(syncTask).then(syncTask => syncTask());
    }
    createAsyncTask(() => {
      console.log('我變成了異步任務(wù)?。?!');
      return 1 + 1;
    }).then(res => {
      console.log(res);
    });
    console.log('我是同步任務(wù)!');

要求:多張圖片加載完之后才能進(jìn)行統(tǒng)一展示

    const loadImg = src => {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.src = src;
            img.onload=()=>{
                resolve(img);
            };
            img.onerror=(e)=>{
                reject(e);
            };
            // img.onload = void resolve(img);
            // img.onerror = void reject('加載失敗');
        });
    };

    const imgs = [
        'http://img1.sycdn.imooc.com\/climg/5b16558d00011ed506000338.jpg',
        'http://img1.sycdn.imooc.com\/climg/5b165603000146ca06000338.jpg',
        'http://img1.sycdn.imooc.com//climg/5b1656140001c89906000338.jpg'
    ];

    // map遍歷數(shù)組中的每一項(xiàng)
    Promise.all(imgs.map(src => loadImg(src))).then(arr => {
        console.log(arr);
        arr.forEach((img)=>{
            document.body.appendChild(img);
        });
    });
    // map遍歷數(shù)組中的每一項(xiàng)(與上面相同作用,,上面是簡(jiǎn)寫)
    // map進(jìn)行循環(huán),每循環(huán)一次就將src作為參數(shù)傳遞進(jìn)來
    // const promises=imgs.map(src =>{
    //     return loadImg(src);
    // });
    // Promise.all(promises).then(arr => {
    //     console.log(arr);
    //     arr.forEach((img)=>{
    //         document.body.appendChild(img);
    //     });
    // }).catch((e)=>{
    //     console.log(e);
    // });

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,,所有內(nèi)容均由用戶發(fā)布,,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式,、誘導(dǎo)購(gòu)買等信息,,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,,請(qǐng)點(diǎn)擊一鍵舉報(bào),。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多