How do promises work in JavaScript?

前端 未结 4 546
时光取名叫无心
时光取名叫无心 2020-11-28 09:06

I just implemented my first function that returns a promise based on another promise in AngularJS, and it worked. But before I decided to just do it, I spent 2 hour

4条回答
  •  旧巷少年郎
    2020-11-28 09:24

    Probably the simplest example of promises usage looks like that:

    var method1 = (addings = '') => {
      return new Promise(resolve => {
        console.log('method1' + addings)
        resolve(addings + '_adding1');
      });
    }
    var method2 = (addings = '') => {
      return new Promise(resolve => {
        console.log('method2' + addings)
        resolve(addings + '_adding2');
      });
    }
    
    method1().then(method2).then(method1).then(method2);
    // result:
    // method1            
    // method2_adding1    
    // method1_adding1_adding2
    // method2_adding1_adding2_adding1
    

    That's basic of basics. Having it, you can experiment with rejects:

    var method1 = (addings = '*') => {
      return new Promise((resolve, reject) => {
        console.log('method1' + addings)
        resolve(addings + '_adding1');
      });
    }
    var method2 = (addings = '*') => {
      return new Promise((resolve, reject) => {
        console.log('method2' + addings)
        reject();
      });
    }
    var errorMethod = () => {
      console.log('errorMethod')
    }
    method1()
    .then(method2, errorMethod)
    .then(method1, errorMethod)
    .then(method2, errorMethod)
    .then(method1, errorMethod)
    .then(method2, errorMethod);
    // result:
    // method1*           
    // method2*_adding1
    // errorMethod
    // method2*
    // errorMethod
    // method2*
    

    As we can see, in case of failure error function is fired (which is always the second argument of then) and then next function in chain is fired with no given argument.

    For advanced knowledge I invite you here.

提交回复
热议问题