0

node.js コードを使用して、A リポジトリからイメージをダウンロードし、B リポジトリにアップロードする関数を作成しています。他のタスクを続行する前に、すべてのストリームを強制的に完了させたいと考えています。私はこの方法を試しましたが、うまくいきませんでした。例: 実行すると、 getImageが実行されます。getImageが完了していない場合、完了するまで A->B->C をループし、その後 getImage を完了します。他のタスクを続行する前に、すべてのストリームを強制的に完了するにはどうすればよいですか? つまり、A->B->C を実行する前にgetImageを終了させたいということです。

PS: pkgCloud を使用してイメージを IBM Object Storage にアップロードしています。

function parseImage(imgUrl){
    var loopCondition = true;
    while(loopCondition ){
       getImages(imgUrl,imgName);
       Do task A
       Do task B
       Do task C
   }
}    

function getImages(imgUrl, imgName) {
    //Download image from A repository
    const https = require('https');
    var imgSrc;
    var downloadStream = https.get(imgUrl, function (response) {

      // Upload image to B repository.
      var uploadStream = storageClient.upload({container: 'images', remote: imgName});
      uploadStream.on('error', function (error) {
        console.log(error);
      });
      uploadStream.on('success', function (file) {

        console.log("upload Stream>>>>>>>>>>>>>>>>>Done");
        console.log(file.toJSON());
        imgSrc = "https://...";
      });
      response.pipe(uploadStream);
    });
    downloadStream.on('error', function (error) {
      console.log(error);
    });
    downloadStream.on('finish', function () {
      console.log("download Stream>>>>>>>>>>>>>>>>>Done");
    });
   return imgSrc;
  }
4

1 に答える 1

0

同期機能と非同期機能の違いを理解する必要があります。getImages 関数は非同期コードを実行しているため、この関数の結果を使用する場合は、ストリーミングが終了したときに呼び出されるコールバックを渡す必要があります。そんな感じ:

  function parseImage(imgUrl) {
    getImages(imgUrl, imgName, function (err, imgSrc) {
      if (imgSrc) {
        Do task A
      } else {
        Do task B
      }
    });
  }

  function getImages(imgUrl, imgName, callback) {
    //Download image from A repository
    const https = require('https');
    var imgSrc;

    var downloadStream = https.get(imgUrl, function (response) {
      // Upload image to B repository.
      var uploadStream = storageClient.upload({ container: 'images', remote: imgName });
      uploadStream.on('error', function (error) {
        console.log(error);
        return callback(error);
      });

      uploadStream.on('success', function (file) {
        console.log("upload Stream>>>>>>>>>>>>>>>>>Done");
        console.log(file.toJSON());
        imgSrc = "https://...";

        return callback(null, imgSrc);
      });

      response.pipe(uploadStream);
    });

    downloadStream.on('error', function (error) {
      console.log(error);
      return callback(error);
    });

    downloadStream.on('finish', function () {
      console.log("download Stream>>>>>>>>>>>>>>>>>Done");
    });
  }
于 2016-10-04T06:15:32.097 に答える