Record the practice of Promise

Time:2019-10-23
  • Promise to practice

Promise to practice

The requirement is a common cache, if there is a cache using the cache, no API pull.

1. Chain and clear logic

P.then().then().catch()

What if they don’t want to go back

Promise.reject in then

Promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. promise. Promise

Function still has a callback but returns the whole thing as a Promise.

So here we have async wrap and new Promise.

The async function returns a 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);
          // break then chain,
          // 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);
      });
    }

Recommended Today

The way of nonlinear optimization

Mathematical knowledge 1、 Nonlinear functionLinear function is another name of a function of first degree, then nonlinear function means that the function image is not a function of a straight line.Nonlinear functions include exponential function, power function, logarithmic function, polynomial function and so on. 2、 Taylor expansion1. Taylor formula:Taylor’s formula is to add a_ The […]