2016-05-14 4 views
3

私はclient.uploadpkgcloudに使用してファイルのディレクトリをアップロードしています。すべてのストリームが終了した後でコールバックを実行する最良の方法は何ですか?それぞれのストリームの「終了」イベントを登録し、すべて終了した後にコールバックを実行する組み込みの方法はありますか?それを行うにはすべてのストリームが終了するのを待ちます - ファイルのディレクトリをストリームします

var filesToUpload = fs.readdirSync("./local_path"); // will make this async 

for(let file of filesToUpload) { 
    var writeStream = client.upload({ 
     container: "mycontainer, 
     remote: file 
    }); 
    // seems like i should register finish events with something 
    writeStream.on("finish", registerThisWithSomething); 
    fs.createReadStream("./local_path/" + file).pipe(writeStream); 
} 
+0

などreadFilesStream/promiseFilesのようなメソッドを持っている、NodeDirを見てみましょうあなたがasync.jsを使用することができますこの種の問題。 async.jsが提供するメソッドを 'async.waterfall()'として使うことができます。ある関数の結果は、コールバック引数として別の関数に渡されます。そのドキュメントをチェックアウトする必要があります。 –

答えて

8

一つの方法は、その後、Promise.all()を利用し、各アップロードのPromiseタスクを生成することです。

コードは次のようになり、あなたはES6を使用していると仮定すると:

const uploadTasks = filesToUpload.map((file) => new Promise((resolve, reject) => { 
    var writeStream = client.upload({ 
     container: "mycontainer, 
     remote: file 
    }); 
    // seems like i should register finish events with something 
    writeStream.on("finish", resolve); 
    fs.createReadStream("./local_path/" + file).pipe(writeStream); 
}); 

Promise.all(uploadTasks) 
    .then(() => { console.log('All uploads completed.'); }); 
+0

ありがとうございます! – berg

0

関連する問題