需求就是常見的緩存,若是有緩存使用緩存,沒有api拉.ios
1.鏈式,邏輯清晰json
P.then().then().catch()axios
2.then chain若是中間不想返回了怎麼辦api
Promise.reject in thenpromise
3.Promisify,既支持回調,又支持Promise緩存
就是function仍是有callback可是總體做爲1個Promise返回.async
這裏用async包裝,和new Promise一個效果.函數
async函數就是返回Promise.fetch
fetchImgUrl: async function (url, fn, cached = true) { if (cached) { //Best practice for Promise then chain with async/await .... return await cache.store.getItem(url).then(value => { if (!value) { console.log('1st time'); return api.get(url + '?json=true', {}) } else { fn(value); // 中斷then鏈條, // throw error to stop then chain // throw new Error('Already cached') //or reject , better return Promise.reject('Already cached'); } }).then((response) => { console.log(response) fn(response.data.url); return response.data.url; }).then(response => { cache.store.setItem(url, response) console.log(`cache: ${response} ok`); }).catch(e => { console.log(e); }) } else { return axios.get(url + '?json=true', {}).then((response) => { fn(response.data.url); } ).catch(e=>{ console.log(e); }); }