2017-09-23 76 views
0

我試圖製作一個應用程序,用於從遠程服務器上下載圖像並從這些圖像創建幻燈片。幻燈片部分我已經整理出來了。我的代碼不起作用,因爲我試圖在未完全下載的情況下使用這些圖像。我知道我需要使用承諾,但我無法將其整理出來。我做錯了什麼,我覺得最好在這裏問一個問題,而不是浪費時間來解決這個問題。使用node.js下載多個圖像並等待,直到完成所有請求

var fs = require('fs') 
var request = require('request-promise'); 

function downloadImgs(imageurls){ //imageurls is an array of urls 
    var tempar=[]; 
    var promises=[]; 
    for (var i = 0; i <=imageurls.length; i++) { 
     if(typeof imageurls[i] !== "undefined"){ 
      img=tempfolder+i+'.jpg'; //tempfolder is a global variable 
      tempar.push(img); 
      prom=request(imageurls[i]).pipe(fs.createWriteStream(img)); 
      promises.push(prom); 
     } 

    } 
    Promise.all(promises).then(function(data) { 

     createslideshow(tempar);//create slideshow with downloaded images 

    }); 

}; 

回答

1

你不能鏈.pipe(...).then(...),因爲pipe不返回的承諾。相反,您需要使用以下內容:

... 
let req = request(imageurls[i]); 
req.pipe(fs.createWriteStream(img)); 
promises.push(req); 
+0

謝謝!你每天救了我(一半)! –