Promise實踐
需求就是常見的緩存,如果有緩存使用緩存,沒有api拉.
1.鏈式,邏輯清晰
P.then().then().catch()
2.then chain如果中間不想返回了怎麼辦
Promise.reject in then
3.Promisify,既支持回調,又支持Promise
就是function還是有callback但是整體作爲1個Promise返回.
這裏用async包裝,和new Promise一個效果.
async函數就是返回Promise.
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);
});
}