Binding a promise handler function to an object

后端 未结 4 1005
迷失自我
迷失自我 2020-12-18 19:21

I have some code like:

var bar = foo().then(function success(value) {
  // compute something from a value...
}, function failure(reason) {
  // handle an err         


        
4条回答
  •  鱼传尺愫
    2020-12-18 19:41

    What I found very useful is to bind each then()'s [function] handler to the one empty object, so each function could have the access to it. Then the user can set and get the properties in each Promise by this keyword. The unit test frameworks works similarly.

        chainPromiseList([getName,getAge],finalDone,rejectHandle);
    
        function chainPromiseList(promiseList,finalDone,errHandle){
          var userContext = new UserContext();
          if(typeof finalDone==='function') promiseList.push(finalDone);
          if(typeof errHandle==='function') promiseList.push(errHandle);
          return promiseList.reduce((total,curVal,curInd,arr)=>{
            var last = curInd+1===arr.length;
            var method = last&&typeof errHandle==='function' ? 'catch':'then';
            var concatenated = total[method](curVal.bind(userContext));
            return concatenated;
          },Promise.resolve());
            function UserContext(){};
        }
        
        function getName(){
          return new Promise((resolve,reject)=>{
            setTimeout(()=>{
              console.log('got name!');
              this.name = 'Paul';
              resolve();
            },500);
          });
        }
    
        function getAge(){
          return new Promise((resolve,reject)=>{
            setTimeout(()=>{
              console.log('got age!');
              this.age = 26;
              resolve();
            },500);
          });
        }
    
        function finalDone(){
          console.log(`Hello, I'm ${this.name} and I'm ${this.age}yo.`);
        }
    
        function rejectHandle(msg){
          console.log('Error: ',msg);
        }

提交回复
热议问题