Javascript 在LearnyYouNode 9上,这两种解决方案的区别是什么?

Javascript 在LearnyYouNode 9上,这两种解决方案的区别是什么?,javascript,Javascript,有人能解释一下下面这两种解决方案的区别吗?在我看来,两种解决方案的逻辑是相同的。但第一种解决方案是正确的,第二种则不然。我知道这与数组的索引有关,但无法理解其背后的逻辑 正确: const http = require('http'); const bl = require('bl'); let count = 0; const message = []; for (let i = 0; i < 3; i++) { let currentIndex = i http.g

有人能解释一下下面这两种解决方案的区别吗?在我看来,两种解决方案的逻辑是相同的。但第一种解决方案是正确的,第二种则不然。我知道这与数组的索引有关,但无法理解其背后的逻辑

正确:

const http = require('http');
const bl  = require('bl');
let count = 0;
const message = [];

for (let i = 0; i < 3; i++) {
    let currentIndex = i
    http.get(process.argv[2+i], (res) => {
    res.pipe(bl((err,data) => {
        if (err) {
            return console.error(err)
        }
        message[currentIndex] = data.toString()
        count++

        if(count === 3) {
            for (let i = 0; i < 3; i++) {
                console.log(message[i])
            }
        }
    }))
  })
}
consthttp=require('http');
常数bl=要求('bl');
让计数=0;
常量消息=[];
for(设i=0;i<3;i++){
设currentIndex=i
http.get(process.argv[2+i],(res)=>{
资源管道(bl)(错误,数据)=>{
如果(错误){
返回控制台。错误(err)
}
message[currentIndex]=data.toString()
计数++
如果(计数==3){
for(设i=0;i<3;i++){
console.log(消息[i])
}
}
}))
})
}
失败:

consthttp=require('http');
常量bl=需要('bl')
让计数=0;
常量消息=[];
for(设i=0;i<3;i++){
http.get(process.argv[2+i],(res)=>{
资源管道(bl)(错误,数据)=>{
如果(错误){
返回控制台。错误(err)
}
message[count]=data.toString()
计数++
如果(计数==3){
for(设i=0;i<3;i++){
console.log(消息[i])
}
}
}))
})
}

关键区别在于,第一种解决方案并不是假设响应将以与请求相同的顺序返回,而是第二种解决方案做出了这样的假设。这是一个危险的假设,所以合理地考虑第一个解决方案是正确的,但是第二个解决方案是不正确的。 这就是说,
currentIndex
变量在第一个解决方案中完全没有意义,可以使用
i
(因为它是用
let
for
中声明的)

下面是一个稍微简化的示例,显示了不同之处:

//用于替代异步部分的实用函数
函数doAsyncThing(索引、回调){
//响应索引===1需要800毫秒,
//但是对于其他任何一个,只有200毫秒
setTimeout(回调,索引===1?800:200,`response${index}`);
}
//第一个解决方案稍微简化了,使用了多种方法
//添加了缺少的分号
函数firstSolution(){
让计数=0;
常量消息=[];
for(设i=0;i<3;i++){
设currentIndex=i;
doAsyncThing(i,结果=>{
消息[currentIndex]=结果;
++计数;
如果(计数==3){
for(设i=0;i<3;i++){
console.log(消息[i]);
}
}
});
}
}
//但使用“count”而不是“currentIndex”`
函数secondSolution(){
让计数=0;
常量消息=[];
for(设i=0;i<3;i++){
doAsyncThing(i,结果=>{
消息[计数]=结果;
++计数;
如果(计数==3){
for(设i=0;i<3;i++){
console.log(消息[i]);
}
}
});
}
}
log(“第一个解决方案:”);
第一个解决方案();
设置超时(()=>{
log(“第二个解决方案:”);
第二种解决方案();

}, 1000);const http = require('http'); const bl = require('bl') let count = 0; const message = []; for (let i = 0; i < 3; i++) { http.get(process.argv[2+i], (res) => { res.pipe(bl((err,data) => { if (err) { return console.error(err) } message[count] = data.toString() count++ if(count === 3) { for (let i = 0; i < 3; i++) { console.log(message[i]) } } })) }) }