循环中的promises有问题。整个承诺对我来说是全新的,所以我尝试用非常简单的例子来学习它。
在我的例子中,我在服务器上有2个文本文件,我想将文本文件的内容保存到数组中。
它适用于setTimeout,但这不是我想要的解决方案。以下是机智setTimeout
的示例var http = require('http'),
Q = require('q');
var urls = ["http://localhost:8000/1.txt", "http://localhost:8000/2.txt"]
var txts = [];
function getData(url) {
http.get(url, function(res) {
var data = "";
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
txts.push(data);
});
}).on('error',function(e){
console.log("Error Request: "+e.message);
})
}
function getTxts() {
for(a in urls) {
var url = urls[a];
getData(url);
}
// is not working
console.log(txts);
// is working
setTimeout(function() {
console.log(txts);
}, 1000)
}
getTxts();
我现在尝试用Q做,但我在某些时候陷入困境。有一点我会走错方向,但我看不出它在哪里。
var http = require('http'),
Q = require('q');
var urls = ["http://localhost:8000/1.txt", "http://localhost:8000/2.txt"]
var txts = [];
function getData(url) {
return Q.promise(function(respond,reject){
http.get(url, function(res) {
var data = "";
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
txts.push(data);
});
}).on('error',function(e){
console.log("Error Request: "+e.message);
})
});
}
function getTxts() {
var promises = [];
for(a in urls) {
var url = urls[a];
var promise = getData(url);
promises.push(promise);
}
return promises;
}
function start() {
Q.fcall(function() {
getTxts();
}).then(function() {
console.log(txts);
})
}
start();
感谢您的帮助!
答案 0 :(得分:2)
你可以使用这个
的常规承诺var http = require('http');
var urls = ["http://localhost:8000/1.txt", "http://localhost:8000/2.txt"]
function getData(url) {
return new Promise(function(resolve, reject) {
http.get(url, function(res) {
var data = "";
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
resolve(data);
});
}).on('error',function(err){
reject(err);
});
});
}
function getTxts() {
return Promise.all(
urls.map(function(url) {
return getData(url);
})
);
}
getTxts().then(function(texts) {
// "texts" is an array of the returned data
}).catch(function(err) {
// epic fail
});
答案 1 :(得分:1)
问题是您没有解析或拒绝您在getData函数中创建的承诺
function getData(url) {
return Q.promise(function(resolve,reject){
http.get(url, function(res) {
var data = "";
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
txts.push(data);
resolve(); // resolve the promise when done
});
}).on('error',function(e){
console.log("Error Request: "+e.message);
reject(); // reject the promise if there is an error
})
}); }