2016-10-04 65 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功能 –

相關問題