gpt4 book ai didi

javascript - '杂耍异步' - 为什么我的解决方案根本不返回任何内容?

转载 作者:行者123 更新时间:2023-11-30 17:11:30 26 4
gpt4 key购买 nike

在针对 learnyounode 中的“Async Juggling”作业要求我做的事情提出问题并获得非常有帮助的答案后,我开始自己实现它。

问题是,我的设置没有成功!尽管我已经提到了其他解决方案,但当我执行 learnyounode verify myscript.js 时,我的设置根本没有返回任何结果。

GIST: jugglingAsync.js

var http = require('http');

var app = (function () {
// Private variables...
var responsesRemaining,
urls = [],
responses = [];

var displayResponses = function() {
for(var iterator in responses) {
console.log(responses[iterator]);
}
};

// Public scope...
var pub = {};

pub.main = function (args) {
responsesRemaining = args.length - 2;

// For every argument, push a URL and prep a response.
for(var i = 2; i < args.length; i++) {
urls.push(args[i]);
responses.push('');
}

// For every URL, set off an async request.
for(var iterator in urls) {
var i = iterator;
var url = urls[i];

http.get(url, function(response) {
response.setEncoding('utf8');

response.on('data', function(data) {
if(response.headers.host == url)
responses[i] += data;
});

response.on('end', function() {
if(--responsesRemaining == 0)
displayResponses();
});
});
}
};

return pub;
})();

app.main(process.argv);

问题:我做错了什么?

最佳答案

这一行

    for(var iterator in urls) {

并没有按照您的想法行事。它实际上遍历 urls 的属性(参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in )。相反,你必须做类似的事情

    for(var i = 0; i < urls.length; i++) {
var url = urls[i];
...
}

    urls.forEach(function(url, index) {
...
});

关于javascript - '杂耍异步' - 为什么我的解决方案根本不返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914849/

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