PouchDB快速搜索:在for循环中搜索并返回结果AFTER for loop finish

时间:2016-11-03 17:14:27

标签: for-loop asynchronous pouchdb quick-search

我有以下文档结构:

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

Tags字段将文档的信息存储在列表中。这种结构需要保持这样。现在,用户有机会在HTML文本输入字段中搜索汽车,其中,表示汽车之间的分隔。我们来看以下示例:

黑色奥迪,粉色奥迪A4

在这里,用户想要找到黑色奥迪或粉红色奥迪A4。我通过数据库查询的方法是将输入的单词拆分为以下结构[["black", "Audi"],["pink", "Audi", "A4"]],并在数据库中的每个文档的Tags字段内搜索 all 单词在一个子阵列中(例如"黑"和#34;奥迪")存在并返回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)
   });

我的问题

我现在的问题是在for循环结束之前返回结果。这可能是因为它是一个异步过程,结果应等待返回此异步完成。但我不知道如何实现这一目标。我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

感谢Nolan Lawson's Blog (Rookie Mistake#2)我能搞清楚。我使用

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