0

モジュールを適切に使用する方法について少し混乱していasyncます。私が持っているとしましょう:

result = long_sync_io_function();
short_sync_function(result);
... //other stuff dependent on result

通常、Node ではlong_sync_io_function()対応する非同期ノードに変換し、long_async_io_function(callback(err, result))次のようにします。

long_async_io_function(function(err, result) {
    if (!err) {
         short_sync_function(result);
         ...//other stuff dependent on result
    }
});

しかし、コールバックを常に埋め込むということは、すぐに大量のインデントを意味します。正しい使用方法は次のasyncとおりです。

//1
async.waterfall([
    function(callback) {
        result = long_sync_io_function();
        callback(null, result);
    },
    function(result, callback) {
        short_sync_function(result);
        //other stuff dependent on result
    }
]);

また

//2
async.waterfall([
    function(callback) {
        long_async_io_function(callback);
    },
    function(result, callback) {
        short_sync_function(result);
        ...//other stuff dependent on result
    }
]);

これらは同等ですか?aysnc1のように非同期コードを作成するのに役立つのか、2 のように既存の非同期コードを構造化するのに役立つだけなのかはわかりません。

4

1 に答える 1

2

非同期ライブラリには、非同期関数/コードを作成する機能がありません。代わりに、既に非同期になっているコードの高次構造/組織のヘルパーとして意図されています。

というわけで2号です。


追加回答

ネストされたコールバックを単に回避するために、非同期ライブラリを使用する必要はありません。インラインで宣言する代わりに、関数に名前を付けるだけです。したがって、代わりに:

long_async_io_function(function(err, result) {
    if (!err) {
         //..do stuff dependent on result
         another_async_function(function(err,result) {
            //..do other stuff
         });
    }
});

次のように記述できます。

function do_other_stuff (err, result) {
    //..
}

function do_stuff_with_io_result (err, result) {
    //..
    another_async_function(do_other_stuff);
}

long_async_io_function(do_stuff_with_io_result );

do stuff with resultこれにより、コードが自己文書化され、デバッグがはるかに簡単になります (特に、デバッガーでステップ実行する場合やスタック トレースを確認する場合)。したがって、や などの冗長なコメントを削除できますdo other stuff

于 2013-08-13T18:03:57.327 に答える