1

The snippet is from the link https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch3.md#finally, I pasted it below:

// 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;
    };
}

Here's how we'd use it in the timeout example from before:

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
] )

What this line Promise.resolve( err ).then( cb ); do? Why not simply use console.log() to print the msg/err? And why cd passed to then called cleanup?

  • I think this line `Promise.resolve( err ).then( cb );` is for the program to deal with other synchronous steps as the cleanup processes are not very important. – Hao Zonggang Jul 15 '20 at 12:27

2 Answers2

0

This is used in libraries, or in domain code, so by this snippet you bubble up the error and let the app manage it. The app decides then if it is logged in console, or if a special behaviour is needed.

djleop
  • 687
  • 4
  • 18
  • Application are often a multilayer code, the Promise remain in a relatively deep layer, and is not used directly in UI. So, bubble up the error is, make the error of a sublayer go up through layers, so that presentation layer can do what is needed in case of error. – djleop May 22 '20 at 07:02
  • So this line `Promise.resolve( msg ).then( cb );` is used to bubble up the message? Why it has to be a promise? How the `cb` does the cleanup since it's called `cleanup`? Is the cleanup means garbage collecting the unused promise? – Hao Zonggang May 22 '20 at 15:16
  • Richytong's answer explains better your last questions. The library is all about promises and it is not surprising that a promise is used. And cleanup is in your code, it means what you need. – djleop May 23 '20 at 08:54
  • What you said about bubbling up messages makes sense now, thanks. – Hao Zonggang May 31 '20 at 05:11
0

Promise.observe takes a Promise pr and a callback function cb and returns the original promise pr. Then, all it does is call cb when pr either resolves (executed successfully) or rejects (threw error). If pr resolved, cb is called with the value wrapped inside pr. If pr rejected, cb is called with the rejected Error.

Example

const sleepThenResolveHello = ms => new Promise(resolve => {
  setTimeout(() => resolve('hello'), ms)
})

Promise.observe(
  sleepThenSayHello(1000),
  message => {
    console.log(message) // > hello
  },
) // == Promise { 'hello' }

What does this line Promise.resolve( err ).then( cb ); do?

That line specifically wraps err in a Promise and passes it to cb

Why not simply use console.log() to print the msg/err?

console.log and Promise.observe are inherently different in what they do. You can for example use console.log inside Promise.observe like in the example above.

And why is cb passed to then called cleanup?

The callback passed to then is called cleanup because the writer of the book had a preconception that the callbacks used in Promise.observe would typically be cleanup functions (like a function that would clean up after the promise pr). This is implied in the implementation; if cb is passed either a value or an error, it might as well take no arguments at all (which is typical of a cleanup function)

richytong
  • 2,387
  • 1
  • 10
  • 21
  • Tell me more about cleanup functions, or is there a web link that introduces cleanup functions? Thanks. – Hao Zonggang May 31 '20 at 05:05
  • Here are some [examples of cleanup functions](https://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits). They usually perform any administrative tasks associated with a given workload – richytong May 31 '20 at 07:03