javascript - 如何理解 YDKJS Promise.observe 片段
问题描述
该片段来自链接https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch3.md#finally,我将其粘贴在下面:
// polyfill-safe guard check
if (!Promise.observe) {
Promise.observe = function(pr,cb) {
// side-observe `pr`'s resolution
pr.then(
function fulfilled(msg){
// schedule callback async (as Job)
Promise.resolve( msg ).then( cb );
},
function rejected(err){
// schedule callback async (as Job)
Promise.resolve( err ).then( cb );
}
);
// return original promise
return pr;
};
}
以下是我们在之前的超时示例中使用它的方式:
Promise.race( [
Promise.observe(
foo(), // attempt `foo()`
function cleanup(msg){
// clean up after `foo()`, even if it
// didn't finish before the timeout
}
),
timeoutPromise( 3000 ) // give it 3 seconds
] )
这条线Promise.resolve( err ).then( cb );
是做什么的?为什么不简单地使用 console.log() 来打印msg
/ err
?为什么cd
传递给then
call cleanup
?
解决方案
Promise.observe
接受一个 Promisepr
和一个回调函数cb
并返回原始的 promise pr
。然后,它所做的只是在解决(成功执行)或拒绝(抛出错误)cb
时调用。pr
如果已pr
解决,cb
则使用包装在 中的值调用pr
。如果pr
被拒绝,cb
则使用被拒绝的错误调用。
例子
const sleepThenResolveHello = ms => new Promise(resolve => {
setTimeout(() => resolve('hello'), ms)
})
Promise.observe(
sleepThenSayHello(1000),
message => {
console.log(message) // > hello
},
) // == Promise { 'hello' }
这行 Promise.resolve(err).then(cb); 是什么?做?
该行专门包装err
在 Promise 中并将其传递给cb
为什么不简单地使用 console.log() 来打印
msg
/err
?
console.log
并且Promise.observe
在他们所做的事情上本质上是不同的。例如,您可以在上面的示例中使用console.log
inside Promise.observe
。
为什么
cb
传递给 then 调用cleanup
?
传递给 then 的回调被调用是cleanup
因为本书的作者有一个先入之见,即其中使用的回调Promise.observe
通常是清理函数(就像在 promise 之后清理的函数pr
)。这在实现中是隐含的;如果cb
传递了一个值或一个错误,它可能根本不接受任何参数(这是清理函数的典型特征)
推荐阅读
- python - Keras 模型误解了输入数据的形状
- python - 在多索引熊猫中,外部索引升序,内部索引降序
- c++ - 我可以调整被移动的向量的大小吗?
- c - 通过 memcpy 将数据从用户应用程序复制到内核驱动程序
- java - 使用 Spring Boot 连接到 MySQL 数据库时出现问题
- kubernetes - 如何在 GCP 上使用 Calico 启用对我的 Kubernetes 服务的外部访问?
- python - 为什么 Pandas 不在 excel 中创建新工作表?
- r - 将字符串拆分为 4 个字符,用逗号分隔
- java - 尝试打印 postorder 和 inorder 但不知道该怎么做
- laravel - Laravel/PHP/Carbon 将日期解析为从 now() 到小时的一到三天,不考虑分钟和秒