有没有办法在运行其他代码之前等待异步函数完成?

时间:2021-07-14 09:29:58

标签: javascript node.js arrays asynchronous

我一直在尝试创建一个网页抓取工具,它需要处理页面上的链接,然后将它们推送到数组中。但是,它是一个异步函数(根据 axios 的要求),因此在其他一些代码尝试处理尚未被异步函数填充(并且为空白)的数组之前,它无法推送到数组。我该如何解决这个问题?

这是我目前的代码:

findLinks().then((array) => { // findLinks is my other function which is also async and finds the links for processing
  const paperPages = []; // The array which is meant to store the processed links
  array.forEach((e) => {
    getPapersLink(e)
      .then((pages) => {
        if(typeof pages === "undefined") return
        paperPages.push(pages.replace("fingerprints", "publications")); // This line is meant to push the links to the "paperPages" array after we've processed them (replaced some stuff)
      })
      .then(() => { // Test function, just logs the array. Since this is in a foreach loop, the array is continuously logged to the console
        console.log(paperPages);
        console.log("========================================")
      });
  });
});

// other code to handle the array which is outputted by the above code is meant to be here
// however :
console.log(paperPages);
// outputs "[]" (without the quotes), the original blank array

我无法将更多项目链接到 .then(),因为它只会一遍又一遍地重复。

感谢帮助!

0 个答案:

没有答案
相关问题