首页 > 解决方案 > 如何理解 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传递给thencall cleanup

标签: javascriptpromise

解决方案


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.loginside Promise.observe

为什么cb传递给 then 调用cleanup

传递给 then 的回调被调用是cleanup因为本书的作者有一个先入之见,即其中使用的回调Promise.observe通常是清理函数(就像在 promise 之后清理的函数pr)。这在实现中是隐含的;如果cb传递了一个值或一个错误,它可能根本不接受任何参数(这是清理函数的典型特征)


推荐阅读