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 回答