我撰寫了一個與Promise API完全分離但實作類似目標的庫。它使用window.requestAnimationFrame并回退到setTimeout并且與 Promises 沒有任何共同之處。事實上,你可以在 ie9 - 10 或 2009 年的機器上運行它。這是源代碼
下面的代碼如何作業,并且第二個承諾在 10 秒延遲后將值 (v 3) 正確地放入第三個承諾中?因為rafx.async...回傳自定義專有物件。
const x = Promise.resolve()
.then(() => console.log("2nd promise"))
.then(() => {
//600 frames === 10 secs
return rafx.async(6)
.skipFrames(600)
.then(v => v 1)
.then(v => v 3);
});
console.log(x instanceof Promise);
x.then(v => console.log("3rd promise", v));
<script src="https://cdn.jsdelivr.net/npm/rafx"></script>
期望 v atx.then(v...將等于從 custom 回傳的任何自定義物件then。
這是rafx.async(6).skipFrames(600)...then(v => v 3)回傳的內容:
prt.Thenable {....
status: Status {thenable: prt.Thenable, instance: Rafx...
_argObj: {value: 10, done: true},
_breaker: {value: false}
....
在Thenable和Status構造都無關Promises,他們是完全自定義的。
令我驚訝的是,這甚至有效:
const x = Promise.resolve()
.then(() => console.log("2nd promise"))
.then(() => {
return rafx.async("hello")
.loop(function(str){
return str;
})
.until(str => window.testVar === " world!")
.then(str => str window.testVar);
});
console.log(x instanceof Promise);
x.then((value) => console.log("3rd promise", value))
.catch((e) => console.log(e));
<script src="https://cdn.jsdelivr.net/npm/rafx"></script>
<button onclick="window.testVar = ' world!';">set testVar to ' world!'</button>
您可以驗證Promise.prototype.then !== rafx.Thenable.prototype.then的then實作是完全獨立的,因為看到這里;
那么怎么可能Promise理解我的 API是如何作業的????(我確定我遺漏了一些非常清楚的東西)
PS:我this用常規的替換了所有的箭頭函式(因為系結),它仍然有效,但它不應該......
uj5u.com熱心網友回復:
Promises 的規范被設計成可以與其他“thenables”互操作。即,具有.then作為函式的屬性的物件。如果您使用 thenable 決議承諾(在您的情況下通過在.then塊中回傳 thenable ),外部承諾將呼叫該函式,傳入決議和拒絕函式,并將等待內部 thenable 呼叫決議。只有這樣,外部的承諾才會解決。
例如:
const promise = new Promise((resolve, reject) => {
const myThenable = {
then: (resolve2, reject2) => {
console.log('running .then')
setTimeout(() => {
console.log('resolving inner');
resolve2("hello");
}, 1000)
}
}
console.log('resolving outer');
resolve(myThenable);
})
promise.then(result => {
console.log('final result', result);
})
然后,您為 thenable 獲得的代碼并非旨在與此一起使用,但顯然它確實可以:
prt.Thenable.prototype.then = function(f, rest){
當承諾呼叫您的.then函式時,f將是決議函式,rest并將是拒絕函式。在您正在呼叫的道路上的某些點f,它恰好具有您想要的行為,并且顯然它沒有導致任何例外rest成為您沒想到的功能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/357527.html
標籤:javascript 异步 承诺 es6-promise
上一篇:如果文本框為空設定邊框為紅色,如果我們輸入文本,洗掉紅色邊框
下一篇:JavaScript在setInterval呼叫的函式中使用screen.width或screen.availWidth時未獲取更新值
