2016-10-04 23 views
0

我使用node.js代码来创建一个函数,从存储库下载图像,然后上传到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; 
    } 
+0

哪个函数定义'imgSrc'? 'uploadStream.on('success''? – guest271314

+0

请参阅[同步和异步编程有什么区别(在node.js中)](http://stackoverflow.com/questions/16336367/what-is-the-difference- – guest271314

回答

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"); 
    }); 
    } 
+0

谢谢你现在我了解异步和同步,但与我的上面的代码我如何让代码等待getImage函数完成之前开始做另一个任务 –

+0

@ ThuậnLê我已经重构了你的代码,传递一个回调就可以做到这一点 –

+0

对于错误信息我很抱歉,因为我有一个while循环,所以在运行时它会运行到最后,然后返回运行getImage功能 –

相关问题