今天看到一個中間件,中使用了Promise.resolve,在這里做一下總結:
/** * 使你除了 action 之外還可以發起 promise。 * 如果這個 promise 被 resolved,他的結果將被作為 action 發起。 * 這個 promise 會被 `dispatch` 返回,因此調用者可以處理 rejection。 */ const vanillaPromise = store => next => action => { if (typeof action.then !== 'function') { return next(action) } return Promise.resolve(action).then(store.dispatch) }
Promise.resolve共有四種參數
第一種:不帶任何參數
setTimeout(function () { console.log('three'); }, 0); Promise.resolve().then(function () { console.log('two'); }); console.log('one'); // one two three
相當於一個resolve狀態的promise對象
第二種:普通變量或者普通對象
const p = Promise.resolve('Hello'); p.then(function (s){ console.log(s) }); // Hello
相當於resolve狀態的promise對象
第三種:參數是一個 Promise 實例
如果參數是 Promise 實例,那么Promise.resolve將不做任何修改、原封不動地返回這個實例。
第四種:參數是一個thenable對象
thenable對象指的是具有then方法的對象,比如下面這個對象
let thenable = { then: function(resolve, reject) { resolve(42); } };
Promise.resolve方法會將這個對象轉為 Promise 對象,然后就立即執行thenable對象的then方法。
let thenable = { then: function(resolve, reject) { resolve(42); } }; let p1 = Promise.resolve(thenable); p1.then(function(value) { console.log(value); // 42 });
thenable對象的then方法執行后,對象p1的狀態就變為resolved,從而立即執行最后那個then方法指定的回調函數,輸出 42
來源鏈接:https://www.jianshu.com/p/96080498b4ea