看似無用的 Promise.resolve()
從 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