簡體   English   中英

如何理解 YDKJS Promise.observe 片段

[英]How to understand the YDKJS Promise.observe snippet

該片段來自鏈接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稱為cleanup

這用於庫或域代碼中,因此通過此代碼段您可以冒泡錯誤並讓應用程序管理它。 然后應用程序決定它是否登錄控制台,或者是否需要特殊行為。

Promise.observe接受一個 Promise pr和一個回調 function cb並返回原始pr 然后,它所做的只是在pr解決(成功執行)或拒絕(拋出錯誤)時調用cb 如果pr已解決,則使用包裝在pr中的值調用cb 如果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.logPromise.observe本質上是不同的。 例如,您可以在Promise.observe中使用console.log ,就像上面的示例一樣。

為什么將cb傳遞給然后稱為cleanup

傳遞給 then 的回調稱為cleanup ,因為本書的作者有一個先入之見,即Promise.observe中使用的回調通常是清理函數(如 function 將在pr 7 之后清理)。 這在實現中是隱含的; 如果cb被傳遞了一個值或一個錯誤,它可能根本不需要 arguments (這是清理函數的典型)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM