Created
July 25, 2021 14:18
-
-
Save Lauviah0622/2326463984a777d90ea000f703426005 to your computer and use it in GitHub Desktop.
生菜的 Promise Race 問題
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 填补的安全检查 | |
if (!Promise.observe) { | |
Promise.observe = function(pr,cb) { | |
// 从侧面观察`pr`的解析 | |
pr.then( | |
function fulfilled(msg){ | |
// 异步安排回调(作为Job) | |
Promise.resolve( msg ).then( cb ); | |
}, | |
function rejected(err){ | |
// 异步安排回调(作为Job) | |
Promise.resolve( err ).then( cb ); | |
} | |
); | |
// 返回原本的promise | |
return pr; | |
}; | |
} | |
function foo() { | |
DOM.addEventListener() | |
return new Promise(...) | |
} | |
Promise.race( [ | |
Promise.observe( | |
foo(), // 尝试`foo()` | |
function cleanup(msg) { | |
DOM.removeEventListener() | |
// 在`foo()`之后进行清理,即便它没有及时完成 | |
} | |
), | |
timeoutPromise( 3000 ) // 给它3秒钟 | |
] ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment