Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Last active July 8, 2022 02:04
Show Gist options
  • Save dSalieri/1be484624f081e3f90febe3413210b6d to your computer and use it in GitHub Desktop.
Save dSalieri/1be484624f081e3f90febe3413210b6d to your computer and use it in GitHub Desktop.
Promise.prototype.finally

Реализация Promise.prototype.finally
Имеет зависимость от SpeciesConstructor

/// Практическая копия настоящего Promise.prototype.finally, выполнена в соответствии со спецификацией ECMAScript
Promise.prototype._finally = function(onFinally){
const promise = this;
if(typeof promise !== "object") throw TypeError("Promise.prototype._finally called on non-object");
let thenFinally, catchFinally;
const C = speciesConstructor(promise, Promise);
if(typeof onFinally !== "function"){
thenFinally = onFinally;
catchFinally = onFinally;
}else{
thenFinally = (value) => {
const result = onFinally();
const promise = Promise.resolve.call(C, result);
const valueThunk = () => value;
return promise.then(valueThunk);
}
catchFinally = (reason) => {
const result = onFinally();
const promise = Promise.resolve.call(C, result);
const throwReason = () => {throw reason};
return promise.then(throwReason);
}
}
return promise.then(thenFinally, catchFinally);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment