chaining async method calls - javascript

前端 未结 3 2136
时光取名叫无心
时光取名叫无心 2020-12-06 16:43

You have a prototype object Foo with two async method calls, bar and baz.

var bob = new Foo()

Foo.prototype.bar = function land(callback) {
  setTimeout(fun         


        
3条回答
  •  醉酒成梦
    2020-12-06 17:24

    If you want to avoid callback hell and keep your sanity ES6 promises are the most appropriate approach for the sake of functional programming. You just chain up your sequential asynchronous tasks in the asynchronous timeline just like working in a synchronous timeline.

    In this particular case you just need to promisify your asynchronous functions. Assume that your asynch functions takes a data and a callback like asynch(data,myCallback). Let us assume that the callback is error first type.

    Such as;

    var myCallback = (error,result) => error ? doErrorAction(error)
                                             : doNormalAction(result)
    

    When your asynch function is promisified, you will actually be returned a function which takes your data and returns a promise. You are expected to apply myCallback at the then stage. The return value of myCallback will then be passed to the next stage at where you can invoke another asynch function supplied with the return value of myCallback and this goes on and on as long as you need. So let's see how we shall implement this abstract to your workflow.

    function Foo(){}
    
    function promisify(fun){
      return (data) => new Promise((resolve,reject) => fun(data, (err,res) => err ? reject(err) : resolve(res)));
    }
    
    function myCallback(val) {
      console.log("hey..! i've got this:",val);
      return val;
    }
    
    var bob = new Foo();
    
    Foo.prototype.bar = function land(value, callback) {
      setTimeout(function() {
        callback(false,value*2);  // no error returned but value doubled and supplied to callback
        console.log('bar');
      }, 1000);
    };
    
    Foo.prototype.baz = function land(value, callback) {
      setTimeout(function() {
        callback(false,value*2);  // no error returned but value doubled and supplied to callback
        console.log('baz');
      }, 1000);
    };
    
    Foo.prototype.bar = promisify(Foo.prototype.bar);
    Foo.prototype.baz = promisify(Foo.prototype.baz);
    
    bob.bar(1)
       .then(myCallback)
       .then(bob.baz)
       .then(myCallback)

提交回复
热议问题