简体   繁体   English

在 node.js 中以正确的顺序运行代码

[英]Running code in the proper order in node.js

I'm making a site that compiles articles based on user interests.我正在制作一个根据用户兴趣编译文章的网站。 And I have a backend but I can't get the code to run in the right order basically I have a MongoDB database with users and each user has an email and an array of interests.我有一个后端,但我无法让代码以正确的顺序运行,基本上我有一个包含用户的 MongoDB 数据库,每个用户都有一封电子邮件和一系列兴趣。 The code starts by looping through the users then it loops through the interests and adds a certain amount of articles to recommend for each interest.代码首先遍历用户,然后遍历兴趣并添加一定数量的文章以针对每个兴趣推荐。 But I need to return this data back to the client after I'm done looping through all of the interests but I can't find a way to do this.但是我需要在遍历完所有兴趣后将这些数据返回给客户端,但我找不到这样做的方法。 code:代码:

  //? Get user emails and intrests
  UsersReference.find({}).toArray(function (err, users) {
    for (var i = 0; i < users.length; i++) {
      const user = users[i]
      //? Generate a text blurb for user based off there intresets
      var limit = 10 / user.intrests.length
      for (var j = 0;j < user.intrests.length;j++) {
        axios({
          "method": "POST",
          "url": "https://tidalwaves-news-analytics2.p.rapidapi.com/articles?limit=" + limit,
          "headers": {
            "x-rapidapi-host": "tidalwaves-news-analytics2.p.rapidapi.com",
            "x-rapidapi-key": "SECRET",
            "useQueryString": true
          },
          "data": {
            "url": {
              "query": user.intrests[j]
            },
          }
        }).then((res) => {
          for(var l =0;l < res.data.data.length;l++) {
            blurbs[i] = blurbs[i] + ". " + res.data.data[l].title
          }
        }).catch((err) => {
          console.log(err)
        })
      }
}

Instead of using then() to wait for promise fulfillment, you can wrap your logic in an async function and use the await keyword.您可以将逻辑包装在async函数中并使用await关键字,而不是使用then()等待承诺履行。

It would make your code easier to read and it would fix your issue.这将使您的代码更易于阅读,并且可以解决您的问题。

Example:例子:

async function myFunction() {
  for (const item of items) {
    const result = await axios({...});
    // Do something with `result`....
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM