const prom =
newpromise
((res, rej)
=>);
prom.
then((
)=>);
console.
log(
'fourth');
// first
// second
// fourth
// third
知識點:promise 建構函式是同步執行,promise.then 是非同步執行。
const prom =
newpromise
((res, rej)
=>
,1000);
});const prom2 = prom.
then((
)=>);
console.
log(
'prom'
, prom)
;console.
log(
'prom2'
, prom2)
;settimeout((
)=>
,2000);
// prom promise {}
// prom2 promise {}
// promise
// prom2 promise
知識點:promise 有三種不同的狀態:pending、fulfilled、rejected,一旦狀態更新,就不再改變,只能從pending->fulfilled 或 pending->rejected 。
const prom = new promise((res, rej) => );
prom
.then(res => )
.catch(err => );
// then: 1
知識點:一旦 resolve 和 reject 同時存在,只會執行第乙個,後面的不再執行。
promise.
resolve(1
).then
(res =>).
catch
(err =>).
then
(res =>);
// 1
// 2
知識點:每次 promise 呼叫.then
或catch
時,都會返回乙個新的 promise,從而實現鏈結呼叫。
const promise =
newpromise
((resolve, reject)
=>
,1000)}
)const start = date.
now(
)promise.
then
((res)
=>
)promise.
then
((res)
=>
)// first
// second 1054 third
// second 1054 fourth
知識點:乙個 promise.then
或.catch
可以被多次呼叫,但是此處promise建構函式僅執行一次。 換句話說,一旦promise 的內部狀態發生變化並獲得了乙個值,則隨後對.then
或.catch
的每次呼叫都將直接獲取該值。
const promise = promise.
resolve()
.then((
)=>
)promise.
catch
(console.error)
// [typeerror: chaining cycle detected for promise #]
知識點:.then
或.catch
返回的值不能是 promise 本身,否則將導致無限迴圈。
promise.
resolve()
.then((
)=>).
then
(res =>).
catch
(err =>);
// then: error: error!
知識點:在.then
或.catch
中返回錯誤物件不會引發錯誤,因此後續的.catch
不會捕獲該錯誤物件,您需要更改為以下物件之一:
return promise.
reject
(new
error
('error'))
throw
newerror
('error'
)
因為返回任何非promise值都將被包裝到乙個promise物件中,也就是說,返回new error('error')
等同於返回promise.resolve(new error('error'))
。
promise.
resolve(1
).then(2
).then
(promise.
resolve(3
)).then
(console.log)
// 1
知識點:.then
或.catch
的引數應為函式,而傳遞非函式將導致值的結果被忽略,例如.then(2)
或.then(promise.resolve(3))
。
promise.
resolve()
.then
(function
success
(res)
,function
fail1
(e))
.catch
(function
fail2
(e))
;// fail2: error: error after success
知識點:.then
可以接受兩個引數,第乙個是處理成功的函式,第二個是處理錯誤的函式。.catch
是編寫.then
的第二個引數的便捷方法,但是在使用中要注意一點:.then
第二個錯誤處理函式無法捕獲第乙個成功函式和後續函式丟擲的錯誤。catch
捕獲先前的錯誤。 當然,如果要重寫,下面的**將起作用:
promise.
resolve()
.then
(function
success1
(res)
,function
fail1
(e))
.then
(function
success2
(res)
,function
fail2
(e))
process.
nexttick((
)=>
)promise.
resolve()
.then((
)=>
)setimmediate((
)=>
)console.
log(
'4')
;// 4 1 2 3
知識點:process.nexttick
和promise.then
都屬於微任務,而setimmediate
屬於巨集任務,它在事件迴圈的檢查階段執行。 在事件迴圈的每個階段(巨集任務)之間執行微任務,並且事件迴圈的開始執行一次。
promise知識點小結
斷斷續續學習es6也有一段時間了,趁著開學空閒對知識點做一些小結。談到promise,我們知道,這是社群較理想的非同步程式設計解決方案。想要掌握promise,我們首先要知道其提出原因。promise的提出很好的解決了多個相互依賴的 之間的巢狀問題,比如說c 需要b 的結果,b 需要a 的結果,用傳...
promise和asyn的重要知識點
promise 物件必知的幾個特性 1.promise屬於巨集任務 2.promise的建構函式是同步,而then裡的是非同步的 3.promise狀態不可逆 4.then接收的如果不是函式,會發生穿透 5.promise物件的resolve或者reject乙個promise物件,前乙個promis...
Unity知識點大彙總
指令碼生命週期 每當指令碼被載入時呼叫一次 1.在awake中做一些初始化操作 void awake 在第一次呼叫update之前呼叫一次start,即使取消啟用,再啟用也不會再執行 3.在start中做一些初始化操作 void start 5.在update方法呼叫完之後呼叫 void lateu...