Promise常用方法

2021-10-24 07:26:44 字數 2916 閱讀 8830

<

!doctype html>

"en"

>

"utf-8"

>

"viewport" content=

"width=device-width, initial-scale=1.0"

>

document<

/title>

"../utils.js"

>

<

/script>

<

/head>

"sendmsg()"

>傳送請求<

/button>

// 傳送三個不同的請求,根據三個返回做資料據處理

// 按順序發請求

// 把巢狀promise展開,在第乙個then裡把promise return出來就可以在後面.then了而不用在裡面巢狀了

function

sendmsg()

).then

(resp =>)}

).then

(resp1 =>)}

).then

(resp2 =>).

catch((

)=>)}

<

/script>

<

/body>

<

/html>

<

!doctype html>

"en"

>

"utf-8"

>

"viewport" content=

"width=device-width, initial-scale=1.0"

>

document<

/title>

"../utils.js"

>

<

/script>

<

/head>

"sendmsg()"

>傳送請求<

/button>

// 傳送三個不同的請求,根據三個返回做資料據處理

// 同時傳送三個

function

sendmsg()

)var pro2 = utils.

fetch

('./06.php',)

var pro3 = utils.

fetch

('./06.php',)

// promise.all([ pro1, pro2, pro3 ]).then((values) => )

promise.

race

([ pro1, pro2, pro3 ]).

then

((value)

=>)}

<

/script>

<

/body>

<

/html>

<

!doctype html>

"en"

>

"utf-8"

>

"viewport" content=

"width=device-width, initial-scale=1.0"

>

document<

/title>

"utils.js"

>

<

/script>

<

/head>

"sendmsg()"

>傳送請求<

/button>

// 傳送三個不同的請求,根據三個返回做資料據處理

// 按順序發請求

// 把巢狀promise展開,在第乙個then裡把promise return出來就可以在後面.then了而不用在裡面巢狀了

function

sendmsg()

).then

(resp =>)}

).then

(resp =>).

then

(resp =>)}

).catch((

)=>)}

<

/script>

最後總結個promise的get和post的請求方法

已封裝好,用於utils.js

* 基於promise的ajax get請求

* @param url 請求位址

* @param query 請求要攜帶的引數

* @param isjson 響應資料是否時json格式,預設為true

fetch

(url, query, isjson =

true)=

$&`//引數拼接

} url = url.

slice(0

,-1)

//去掉多餘的拼接符號

}// 把這個promise的例項return出去,才能在呼叫位置.then

return

newpromise

((resolve, reject)

=>

else}}

})},

/** * ajax post請求

* @param url 請求位址

* @param query 請求要攜帶的引數

* @param isjson 響應資料是否為json格式,預設為true

*/fetchpost

(url, query, isjson =

true)=$`}

}return

newpromise

((resolve, reject)

=>

else}}

})}

promise方法總結

優點 1 物件的狀態不受外界的影響,只有非同步操作的結果可以決定是那種狀態 2 狀態一旦改變,就不會再次改變。任何時候都可以得到這個結果。在這裡跟 event 事件不同,如果錯過了這個事件結果再去監聽,是監聽不到event事件的。缺點 1 promise一旦執行無法取消。2 如果不設定 函式prom...

Promise 原始碼 靜態方法

最後來看一下 promise 的幾個常用的靜態方法的實現 注 本次閱讀的是 then promise 的 4.0.0 版本,原始碼請戳 這裡。在 4.0.0 版本之中,promise 物件被封裝在了core.js檔案中,常用的靜態方法則寫在了index.js檔案中,開啟 index.js 檔案。pr...

Promise物件下的方法

請求介面,拿到資料 new promise resolve,reject resolve data 1000 then data return data.data then data reject 與resolve new promise resolve,reject then ctach 作用 捕...