3

非同期パラダイムをまだ理解していないかもしれませんが、次のようなことをしたいと思います。

var exec, start;
exec = require('child_process').exec;
start = function() {
  return exec("wc -l file1 | cut -f1 -d' '", function(error, f1_length) {
    return exec("wc -l file2 | cut -f1 -d' '", function(error, f2_length) {
      return exec("wc -l file3 | cut -f1 -d' '", function(error, f3_length) {
        return do_something_with(f1_length, f2_length, f3_length);
      });
    });
  });
};

新しいシェルコマンドを追加するたびにこれらのコールバックをネストし続けるのは少し奇妙に思えます。それを行うためのより良い方法はありませんか?

4

2 に答える 2

7

Xaviが言ったように、TwoStepを使用できます。一方、私は非同期JSライブラリを使用しています。コードは次のようになります。

async.parallel([
    function(callback) {
        exec("wc -l file1 | cut -f1 -d' '", function(error, f1_length) {
            if (error)
                return callback(error);
            callback(null, f1_length);
        });
    },
    function(callback) {
        exec("wc -l file2 | cut -f1 -d' '", function(error, f2_length) {
            if (error)
                return callback(error);
            callback(null, f2_length);
        });
    },
    function(callback) {
        exec("wc -l file3 | cut -f1 -d' '", callback);
    }
],
function(error, results) {
    /* If there is no error, then
       results is an array [f1_length, f2_length, f3_length] */
    if (error)
        return console.log(error);
    do_something_with(results);
});

非同期には、他にもたくさんのオプションがあります。ドキュメントを読んで試してみてください!を呼び出すときf3_lengthに使用したことに注意してください。これは他の呼び出しでも実行できます(コードが短くなります)。それがどのように機能するかをお見せしたかっただけです。callbackexec

于 2012-05-27T20:16:57.517 に答える
4

私は個人的にこれらの状況でTwoStepを使用します:

var TwoStep = require("two-step");
var exec, start;
exec = require('child_process').exec;
start = function() {
  TwoStep(
    function() {
      exec("wc -l file1 | cut -f1 -d' '", this.val("f1_length"));
      exec("wc -l file2 | cut -f1 -d' '", this.val("f2_length"));
      exec("wc -l file3 | cut -f1 -d' '", this.val("f3_length"));
    },
    function(err, f1_length, f2_length, f3_length) {
      do_something_with(f1_length, f2_length, f3_length);
    }
  );
};

とは言うものの、そこにはたくさんのフロー制御ライブラリがあります。試してみることをお勧めします:https ://github.com/joyent/node/wiki/Modules#wiki-async-flow

于 2012-05-27T19:04:29.027 に答える