gpt4 book ai didi

javascript - 尝试在 for 循环中执行 promise 链(对列表中的每个项目执行一次)——我该如何正确执行此操作?

转载 作者:行者123 更新时间:2023-11-30 14:56:23 25 4
gpt4 key购买 nike

<分区>

我在 Node 的异步特性方面遇到了一些麻烦,我想不出如何解决这个问题。

我正在尝试为集合中的每个项目运行一次整个 promise 链。如果我在集合中只有一个项目,它会完美地工作——但是一旦我添加了第二个项目,结果就会变得很奇怪。

我确定这与异步运行的循环有关,我需要类似 promise.all 的东西,但我不能......弄清楚......它。

基本上,我在配置文件中有一个报告列表。每个报告都有一个路径(和一些其他信息)。看起来像这样:

var reportsCollection = 
{
"reportname1" : {
"filename" : "filename1",
"otheritem" : "etc..."
},
"reportname2" : {
"filename : "filename2",
}
}

对于该集合中的每个报告,我想运行一个 promise 链。

  //Will loop through twice, once with report = "reportname1", once with report = "reportname2"
for(var report in reportsCollection){

console.log("Starting " + report);

self.getReportRows(report, function(retVal){

//does some stuff turning retval into rows
return rows;

}).then(function(rows){

//If I check here,the right number of rows is returned for each report - I get two different values.
console.log(rows.length + "returned");

//The issue is here - the report variable does not refer to the current report, even though we are completing the entire promise chain once for each report. So I get report2 twice.
//I don't understand - should this entire thing not run once for each "report"? Why is it running the first section for each report and then
// running this section multiple times for the last report?!

console.log("uploading "+ rows.length + "rows for " + report + " data to" + reportsConfig[report]["filename"]); //<- always displays reportname2/filename2


})

}); // end reportsConfig for loop

这将显示如下内容:

Starting reportname1         //returns 4 rows
Starting reportname2 //returns 18 rows
uploading 4 rows for reportname2 to filename2
uploading 18 rows for reportname2 to filename2

有人能帮帮我吗?我期待这样的结果

Starting reportname1
Starting reportname2
uploading 4 rows for reportname1 to filename1
uploading 18 rows for reportname2 to filename2

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