记录Promise的实践

Promise实践

需求就是常见的缓存,若是有缓存使用缓存,没有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);
      });
    }
相关文章
相关标签/搜索