-1
我想設置一個快速服務器,返回項目數組查詢的結果。我已閱讀this question,我可以用Promise.each
這個...如何使用Promise發送請求結果數組?
我打算我的代碼做的是:
- 網頁刮一個網頁,電影列表,並返回標題爲數組。
- 使用電影的標題做一個API的請求,對每個
- 返回與API響應每一部電影
這裏的結果給客戶端的響應是我的代碼:
var express = require('express');
var app = express();
var Xray = require('x-ray');
var x = Xray();
app.get('/', function (req,res){
var username = 'medicengonzo';
var pages = 3;
x('https://letterboxd.com/'+username+'/watchlist/', 'li.poster-container', [{
movie: '[email protected]'
}])(function (err,results){
console.log('Entered x-ray callback fn');
results.forEach(function(result, index){
console.log('Iteration');
console.log(results.length);
request('http://netflixroulette.net/api/api.php?title='+encodeURIComponent(result.movie),
function(err, response, body){
movies = [];
console.log(count);
obj = JSON.parse(body);
if(obj.errorcode != 404){
movies.push('Movie found: '+obj.show_title, 'ID: '+obj.show_id);
}
else{
movies.push('No movie found');
}
res.send(movies);
}
);
});
})
.paginate('.paginate-current+li [email protected]')
.limit(pages);
});
app.listen(3000, function(){
console.log('Listening on port 3000!');
});
你的意思是Promise.all? –
目前尚不清楚你的代碼打算做什麼。現在,您正在'results.forEach()'循環內執行一個'res.send(movies)',因此您可以多次執行相同的請求,這絕對是編碼錯誤,只有第一個作爲迴應發送。那麼,你應該發送什麼結果作爲迴應? – jfriend00
@BorisCharpentier我對承諾是新的,所以我不太明白'Promise.all'如何工作... – medicengonzo