Promise thenable All In One_javascriptPromise thenable All In One



Promise thenable All In One

Promise thenable 是指一个函数或一个对象的里面定义了一个 then 方法

Promise thenable All In One_js_02

Promises/A+

Promise thenable All In One_javascript

​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