xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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

https://medium.com/javascript-in-plain-english/whats-the-difference-between-a-thenable-and-a-promise-74d697bc9c79

https://stackoverflow.com/questions/53894038/whats-the-difference-between-resolvethenable-and-resolvenon-thenable-object



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


原文地址:https://www.cnblogs.com/xgqfrms/p/13986080.html