【发布时间】:2023-02-07 01:31:58
【问题描述】:
我正在尝试在 nodejs18 中使用 fetch 的项目中使用 curseforge API,这是我正在使用的代码:
ids = ["238222","60089","556448"]
const headers = {
'Accept':'application/json',
'x-api-key':'API KEY'
};
function getMods(id){
fetch("https://api.curseforge.com" + '/v1/mods/' + id,
{
method: 'GET',
headers: headers
})
.then(function(res) {
return res.json();
}).then(function(body) {
console.log(body.data.name);
});
}
ids.forEach(element => {
getMods(element)
});
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
console.log("download finished")
使用该代码,您希望在终端中打印的内容是:
Alex's Delight
Mouse Tweaks
Just Enough Items (JEI)
download finished
但是在运行程序时,我在终端中得到了这个:
download finished
Alex's Delight
Mouse Tweaks
Just Enough Items (JEI)
发生这种情况是因为 fetch 函数是异步的,我已经尝试了所有的方法来解决这个问题,但没有一个解决方案是我想要的。
我想要的是让程序等待 foreach 和 fetch 完成以继续执行。
【问题讨论】:
-
做出一系列承诺,然后使用
Promise.all()按顺序打印结果。 -
如果 API 密钥是真实密钥,请确保生成一个新密钥并禁用问题中发布的密钥。否则其他人可以使用您的 API 密钥以您的名义进行调用。
标签: javascript node.js fetch-api