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
?