我在 node.js 中使用 Google Trends API 来获取多个搜索词的受欢迎程度。
我想在一个数组中写入多个搜索词,然后访问该数组,为每个元素调用 Google Trends API,并使用 API 结果为每个元素创建一个文件。
我尝试过这个:
const googleTrendsApi = require("google-trends-api");
const fs = require('fs');
var cars = ["Saab", "Volvo", "BMW"];
for(var j = 0; j < 3; j++)
{
googleTrendsApi.interestOverTime({keyword: cars[j]})
.then(function(results){
fs.writeFile(cars[j]+'.txt', results, function (err) {
if (err) return console.log(err);
})
})
.catch(function(err){
console.error(err);
});
console.log(cars[j]);
};
问题是这个方法不起作用(它不创建文件),我不知道为什么。如何在 for 循环中创建多个文件并在每个文件中写入单独的数据?
最佳答案
当您在 for 循环内运行异步方法时,您必须考虑到一旦异步方法返回,索引可能(并且可能会)更改为最后一个索引 (j = 3)。 这是因为异步方法的执行时间可能比 for 循环遍历所有索引的时间长得多。
您可以通过运行自行验证:
for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
输出将为:3 3 3
为了克服这个问题,您可以将 for 循环的主体放在方法中
function execute(j) {
googleTrendsApi.interestOverTime({keyword: cars[j]})
.then(function(results){
fs.writeFile(cars[j]+'.txt', results, function (err) {
if (err) return console.log(err);
})
})
.catch(function(err){
console.error(err);
});
}
然后你的 for 循环将调用execute(j):
for(var j = 0; j < 3; j++)
{
execute(j);
console.log(cars[j]);
}
execute(j) 将确保捕获 j 的上下文,甚至直到异步方法执行之后。
关于javascript - Node.js 在 for 循环中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43499108/