简体   繁体   中英

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. 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.

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`....
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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