モジュールを適切に使用する方法について少し混乱してい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
}
]);
これらは同等ですか?aysnc
1のように非同期コードを作成するのに役立つのか、2 のように既存の非同期コードを構造化するのに役立つだけなのかはわかりません。