/ walking bear:D / 看似無用的 Promise.resolve()

看似無用的 Promise.resolve()

2019-10-23 posted in [筆記]

MDN 的舉例來看 Promise.resolve() 似乎用處不大,傳入 plain value 回一個 resolved 的 Promise object,傳入 Promise object 則原封不動還一個相同的 Promise object,有趣的應用應該是傳入一個 thenable 的 object,如下例:

let thenableObj = {};
thenableObj.then = function(cb) {
    console.log(`thenable : ${cb}`);
    setTimeout(() => {
        cb('hello brave new world! ' + Math.random());
    }, Math.random() * 10000);
}
var promise1 = Promise.resolve(thenableObj);
promise1.then(function(value) {
  console.log('promise1:', value);
});
Promise.resolve(thenableObj).then((v) => console.log(`promise1+:${v}`));

Promise.resolve() 看到傳進來的是 thenable,馬上叫用了 then(),結果如下:

thenable : function () { [native code] }
thenable : function () { [native code] }
promise1+:hello brave new world! 0.2978584825012849
promise1: hello brave new world! 0.373329644074186

再改一個例子澄清概念:

class thenableObject {
        constructor(m = 'Salaam', t = 1000) {
                this.cblist = [];
                setTimeout(() => this.cblist.forEach(cb => cb(`${m} ${Date.now()}`)), t);
        }
        then(cb) {
                this.cblist.push(cb)
        }
};

let to2 = new thenableObject('Shalom');
var p1 = Promise.resolve(to2);
p1.then((v) => console.log(`p1: ${v}`))

Promise.resolve(to2).then(v => console.log(`p2: ${v}`));

執行結果:

p1: Shalom 1571820219172
p2: Shalom 1571820219172

walking bear:DRSS feed

关于

wkliang

Clarke's Three Laws:

  • When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
  • The only way of discovering the limits of the possible is to venture a little way past them into the impossible.
  • Any sufficiently advanced technology is indistinguishable from magic.
  • 版权申明

    知识共享许可协议

    Fork me on GitHub

    Powered by

    Disqus, GitHub, Google Custom Search, Gravatar, HighlightJS, jekyll