【问题标题】:Wait for a fetch function to finish等待获取函数完成
【发布时间】: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


【解决方案1】:

这样的事情可以工作:

...
promisesArray = []
ids.forEach(element => {
  promisesArray.push(getMods(element))
});

Promise.all(promisesArray).then(() => { 
   console.log("download finished");
 });

【讨论】:

  • 你是绝对正确的!我已经编辑了答案。
【解决方案2】:

因为你运行 nodejs 18 你有顶级等待


const headers = {
  'Accept': 'application/json',
  'x-api-key': 'API KEY'
};

async function getMods(id) {
  await 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);
    });
}

const promises = []

ids.forEach(element => {
  promises.push(getMods(element))
});

try {
  await Promise.all(promises)

  console.log("download finished")
} catch {
  // Handle error

  console.error("download error")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-16
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2017-06-22
    • 2021-03-09
    相关资源
    最近更新 更多