乐趣区

记录Promise的实践

  • Promise 实践

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);
      });
    }
退出移动版