Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Lauviah0622/2326463984a777d90ea000f703426005 to your computer and use it in GitHub Desktop.
Save Lauviah0622/2326463984a777d90ea000f703426005 to your computer and use it in GitHub Desktop.
生菜的 Promise Race 問題
// 填补的安全检查
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