chaining async method calls - javascript

前端 未结 3 2134
时光取名叫无心
时光取名叫无心 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:29

    Warning this isn't quite right yet. Ideally we'd subclass Promise and have proper then/catch functionality but there are some caveats with subclassing bluebird Promise. The idea is to store an internal array of promise generating functions, then when a Promise is waited on (then/await) serially wait on those promises.

    const Promise = require('bluebird');
    
    class Foo {
      constructor() {
        this.queue = [];
      }
    
      // promise generating function simply returns called pGen
      pFunc(i,pGen) {
        return pGen();
      }
    
      bar() {
        const _bar = () => {
          return new Promise( (resolve,reject) => {
            setTimeout( () => {
              console.log('bar',Date.now());
              resolve();
            },Math.random()*1000);
          })      
        }
        this.queue.push(_bar);
        return this;
      }
    
      baz() {
        const _baz = () => {
          return new Promise( (resolve,reject) => {
            setTimeout( () => {
              console.log('baz',Date.now());
              resolve();
            },Math.random()*1000);
          })      
        }
        this.queue.push(_baz);
        return this;
      }
    
      then(func) {
        return Promise.reduce(this.queue, this.pFunc, 0).then(func);
      }
    }
    
    
    const foo = new Foo();
    foo.bar().baz().then( () => {
      console.log('done')
    })
    

    result:

    messel@messels-MBP:~/Desktop/Dropbox/code/js/async-chain$ node index.js 
    bar 1492082650917
    baz 1492082651511
    done
    

提交回复
热议问题