gpt4 book ai didi

javascript - Node : Use Promises in Loop with Q

转载 作者:行者123 更新时间:2023-11-30 12:05:53 27 4
gpt4 key购买 nike

我对循环中的 promise 有疑问。整个 promise 对我来说是全新的,所以我尝试通过非常简单的示例来学习它。

在我的示例中,我在服务器上有 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();

感谢您的帮助!

最佳答案

你可以为此使用普通的 promise

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
});

关于javascript - Node : Use Promises in Loop with Q,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35255399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com