Promise详解,相信你看完我这篇文章简单的Promise使用方式基本上就全会了
生活随笔
收集整理的這篇文章主要介紹了
Promise详解,相信你看完我这篇文章简单的Promise使用方式基本上就全会了
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Promise 對象
認識Promise對象
語法
new Promise((resolve, reject)=>{resolve();// reject(); }).then(()=>{console.log("resolve!"); }).catch(()=>{console.log("reject!"); })Promise 對象執行了 resolve 就不執行reject
也就是說,執行了 .then 就不執行 .catch
resolve/reject 類型是 Function
案例1:打印 1-3 每隔500ms
function GetTime() {return new Promise((resolve, reject) => {setTimeout(() => {resolve();}, 500)});}var num = 1;GetTime().then(() => {console.log(num++);return GetTime(); }).then(() => {console.log(num++);return GetTime(); }).then(() => {console.log(num++);return GetTime(); });案例2 做一個簡易的紅綠燈 每個2秒切換燈
<!-- HTML 結構 --> <!doctype html> <html lang="zh_CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>簡易紅綠燈</title> </head> <body><div></div><div></div><div></div> <!--引入一下js--> </body> </html> /*css 樣式*/ *{margin: 0;padding: 0; } div{width: 50px;height: 50px;border: 1px solid #000000;box-shadow: 0px 0px 4px #cccccc inset;border-radius: 50%;margin-left: 20px; } // js var divs = document.querySelectorAll("div");function GetTime(){return new Promise((resolve, reject)=>{setTimeout(()=>{resolve();},2000) }); }GetTime().then(()=>{divs[0].style.backgroundColor = "red";return GetTime(); }).then(()=>{divs[1].style.backgroundColor = "green";divs[0].style.backgroundColor = "rgba(0,0,0,0)";return GetTime(); }).then(()=>{divs[2].style.backgroundColor = "yellow";divs[1].style.backgroundColor = "rgba(0,0,0,0)";return GetTime(); });Promise 三種狀態
pending 剛進入promise狀態
fulfilled 執行了resolve 后
rejected 執行了reject 后
Promise.all()
將所有的Promise對象中resolve 的參數內容合成數組 用于遍歷所有的promise對象Promise.race()
誰快誰先完成Promise.resolve().then(()+>{});
new promise((resolve, reject)=>{resolve(); }).then(()=>{});Promise.reject().catch(()=>{});
new promise((resolve, reject)=>{reject(); }).catch(()=>{});隱士返回一個promise對象
// 這是一個promise對象 loadImage("./img/5-.jpg") .then((img)=>{console.log("aaa", img);// 相當于returnPromise.resolve(); }).then((img)=>{console.log("bbb", img); // 返回的resolve 無參數,所以打印出bbb undefined })async await
語法 :
async function fn(){return "a"; } var p = fn(); log(a) => 得到的一個結果是 Promiseawait 只能等待 promise 執行 resolve 或者 reject 后的內容,并且 await 只能出現在 async 函數中
謝謝觀看,如需幫助請留言,
一鍵三連 支持一下作者
總結
以上是生活随笔為你收集整理的Promise详解,相信你看完我这篇文章简单的Promise使用方式基本上就全会了的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 玩cf人物出现透明怎么解决
- 下一篇: 有道翻译官如何翻译手机网页(如何评价长沙