EventEmitter in the middle of a chain of Promises

前端 未结 1 1291
清歌不尽
清歌不尽 2020-12-05 05:30

I am doing something that involves running a sequence of child_process.spawn() in order (to do some setup, then run the actual meaty command that the caller is

相关标签:
1条回答
  • 2020-12-05 05:58

    There are two approaches, one provides the syntax you originally asked for, the other takes delegates.

    function doAllTheThings(){
         var com = runInterestingCommand();
         var p = new Promise(function(resolve, reject){
             com.on("close", resolve);
             com.on("error", reject);
         });
         p.on = function(){ com.on.apply(com, arguments); return p; };
         return p;
    }
    

    Which would let you use your desired syntax:

    doAllTheThings()
      .on('stdout', function(data){
        // process a chunk of received stdout data
      })
      .on('stderr', function(data){
        // process a chunk of received stderr data
      })
      .then(function(exitStatus){
        // all the things were done
        // and we've returned the exitStatus of
        // a command in the middle of a chain
      });
    

    However, IMO this is somewhat misleading and it might be desirable to pass the delegates in:

    function doAllTheThings(onData, onErr){
         var com = runInterestingCommand();
         var p = new Promise(function(resolve, reject){
             com.on("close", resolve);
             com.on("error", reject);
         });
         com.on("stdout", onData).on("strerr", onErr);
         return p;
    }
    

    Which would let you do:

    doAllTheThings(function(data){
        // process a chunk of received stdout data
      }, function(data){
        // process a chunk of received stderr data
      })
      .then(function(exitStatus){
        // all the things were done
        // and we've returned the exitStatus of
        // a command in the middle of a chain
      });
    
    0 讨论(0)
提交回复
热议问题