Promise thenable All In One
Promise thenable All In One
Promise thenable 是指一个函数或一个对象的里面定义了一个 then 方法
Promises/A+
https://promisesaplus.com/#terminology
https://github.com/then/promise
https://github.com/then/thenable/blob/master/index.js
// Wrapped
function Wrapped(thenable) {
this.val = thenable;
}
Wrapped.prototype.unwrap = function () {
return this.val;
};
// wrap
function wrap(thenable) {
return new Wrapped(thenable);
}
// unwrap
function unwrap(wrapped) {
return wrapped instanceof Wrapped ? wrapped.unwrap() : wrapped;
}
exports.wrap = wrap;
exports.unwrap = unwrap;
ECMA 262
https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob
MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
refs
https://javascript.info/promise-chaining
class Thenable {
constructor(num) {
this.num = num;
}
then(resolve, reject) {
alert(resolve); // function() { native code }
// resolve with this.num*2 after the 1 second
setTimeout(() => resolve(this.num * 2), 1000); // (**)
}
}
new Promise(resolve => resolve(1))
.then(result => {
return new Thenable(result); // (*)
})
.then(alert); // shows 2 after 1000ms
https://masteringjs.io/tutorials/fundamentals/thenable
https://exploringjs.com/es6/ch_promises.html#sec_chaining-promises
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13986080.html
未经授权禁止转载,违者必究!