0

I have the following document structure:

{
  "_id": "car_1234",
  "_rev": "1-9464f5d70547c255a423ff8dae653db1",
  "Tags": [
    "Audi",
    "A4",
    "black"
  ],
  "Car Brand": "Audi",
  "Model": "A4",
  "Color": "black",
  "CarDealerID": "5"
}

The Tags field stores the information of the document in a list. This structure needs to stay like this. Now the user has the opportunity to search for cars in a HTML text input field, where a , represents a separation between cars. Let's take the following example:

black Audi, pink Audi A4

Here the user wants to find a black Audi or a pink Audi A4. My approach of querying through the database is by splitting the entered words to the following structure [["black", "Audi"],["pink", "Audi", "A4"]] and to search inside the Tags field of each document in the db if all the words in a subarray (e.g. "black" and "Audi") are existent and to return the CarDealerID.

 ///Before this I return the word list as described
 }).then(function (wordList) {
 results = [];

 for (var i = 0; i < userWords.length; i++) {

    //Check if the object is a single word or an array of words
    if (wordList[i].constructor === Array) {

         //Recreate the words in the array as one string
         wordString = ""
         wordList[i].forEach(function (part) {
             wordString += part + " "
         })
         wordString = wordString.trim()

         //Search for the car
         car_db.search({
             query: wordString,
             fields: ["Tags"],
             include_docs: true
             }).then(function(result) {
                 result.rows.forEach(function (row) {
                    results.push(row.doc.CarDealerID)
                 })
             })

    } else {
       car_db.search({
           query: userWords[i],
           fields: ["Tags"],
           include_docs: true
           }).then(function(result) {
               result.rows.forEach(function (row) {
                  results.push(row.doc.CarDealerID)
               })
           })
    }

    return results

   }).then(function(results) {
         console.log(results)
   }).catch(function (err) {
         console.log(err)
   });

My Problem

My problem is now that the results are returned before the for loop finishes. This is probably because it is an async procedure and the result should wait to be returned until this async is finished. But I don't know how to achieve that. I hope someone can help me out.

1 Answers1

0

Thanks to Nolan Lawson's Blog (Rookie Mistake #2) I could figure it out. Instead of the for loop, I use

return Promise.all(wordList.map(function (i) {
     results = [];
     //
     //Same Code as before
     //
     //Return results inside the map function
     return results;
}));