【问题标题】:wait for dbpouch and lunar to finish their job等待 dbpouch 和 lunar 完成他们的工作
【发布时间】:2021-01-30 02:03:40
【问题描述】:

这是我在原版 javascript 中的代码:

<html>
<meta charset="utf-8"/>
<script src="//cdn.jsdelivr.net/npm/pouchdb@7.2.1/dist/pouchdb.min.js"></script>
<script src="https://unpkg.com/lunr/lunr.js"></script>
<script>
    var dbp = new PouchDB('my_database');
    var doc = {
        "_id": "mittens",
        "name": "Mittens",
        "occupation": "kitten",
        "age": 3,
        "hobbies": [
            "playing with balls of yarn",
            "chasing laser pointers",
            "lookin' hella cute"
        ]
    };
    //db.put(doc);
    dbp.put(doc);
    var loaded = false;
    var searchIndex;
    dbp.allDocs({include_docs: true}).then((response) => {
        searchIndex = lunr(function () {
            this.ref("_id");
            this.field("name", {boost: 10});


            for (row in response.rows) {
                temp = {
                    "name": response.rows[row].doc["name"],
                    "_id": response.rows[row].doc["_id"]
                };
                this.add(temp);
            }
        });
        console.log("finished");
        loaded = true;
    });

    setTimeout(function () {  //Beginning of code that should run AFTER the timeout
        console.log("done");
        result = searchIndex.search("mittens");
        console.log(result[0]["ref"]);
        //lots more code
    }, 10000);
    console.log(searchIndex.search("mittens"));


</script>

如果我等待 10 秒,搜索就会起作用。我尝试在 dbpouch 搜索之前添加 await,但它不起作用。

如何让我的 vanilla 脚本等待我的 dbpouch 数据库的索引?

因为我有一个:

(index):59 Uncaught TypeError: Cannot read property 'search' of undefined

因为我的搜索还没有准备好。我想找到一种方法让我的脚本等待搜索索引完成。

当我尝试等待 db.put(doc);

我有一个

未捕获的 SyntaxError:await 仅在异步函数和异步中有效 发电机

这是一个 jsfiddle :

https://jsfiddle.net/bussiere/4p1q3L9j/1/

我的主要目标是在 lunar 中加载 dbpouch,然后能够进行多次搜索。

所以只在 lunr 中进行一次 loding,而不是每次我想进行搜索。

问候

【问题讨论】:

    标签: javascript asynchronous pouchdb


    【解决方案1】:

    你的代码有大问题

    dbp.put(doc);
    

    pouchDB 的put 是异步的,因此代码与数据库不同步。

    相反,

    await dbp.put(doc);
    

    或者如果您更喜欢基于 Promise 的方法,

    dbp.put(doc).then((response) => {
       // etc
    });
    

    下面的 sn-p 基于您的代码,使用 async/await。

    更准确地说,allDocs 索引在putbulkDocs 之后准备就绪;但是对于二级索引(map/reduce、mango),这是正确的。为了确保二级索引的完整结果,例如在影响 map/reduce 视图的大批量插入后,以下代码将等待二级索引完全构建。

    await db.query(view_index, { reduce: true });
    

    要查看该技术的实际应用,请考虑this SO Q/A

    // Use memory adapter for testing to avoid having to deal with an existing database
    const db = new PouchDB('my_database', {
      adapter: 'memory'
    });
    // test doc
    const doc = {
      "_id": "mittens",
      "name": "Mittens",
      "occupation": "kitten",
      "age": 3,
      "hobbies": [
        "playing with balls of yarn",
        "chasing laser pointers",
        "lookin' hella cute"
      ]
    };
    // convenience
    const gel = id => document.getElementById(id);
    
    (async() => {
      let header,result;
      // ops
      try {  
        // PUT is async.
        await db.put(doc);
        // allDocs index is ready. Not true for secondary indexes (map/reduce).  
        const response = await db.allDocs({
          include_docs: true
        });
        // setup lunr
        const searchIndex = lunr(function() {
          this.ref("_id");
          this.field("name", {
            boost: 10
          });
          for (row in response.rows) {
            temp = {
              "name": response.rows[row].doc["name"],
              "_id": response.rows[row].doc["_id"]
            };
            this.add(temp);
          }
        });
        // ok, search.   
        result = searchIndex.search("mittens");    
        header = "Search result";
      } catch (err) {
        // conflate error object and search result object.
        result = [err];   
         header = "Error";
      }
      // display result
      gel('header').innerText = header;
      gel('result').innerText = JSON.stringify(result[0], undefined, 3);
    })();
    .hide {
      display: none
    }
    <html>
    <meta charset="utf-8" />
    <script src="//cdn.jsdelivr.net/npm/pouchdb@7.2.1/dist/pouchdb.min.js"></script>
    <script src="https://github.com/pouchdb/pouchdb/releases/download/7.2.1/pouchdb.memory.min.js"></script>
    <script src="https://unpkg.com/lunr/lunr.js"></script>
    
    <body>
      <div id='header'></div>
      <pre id='result'></pre>
    </body>

    更新这是一个基于 Promise 的 sn-p。初始化 db 和 lunr 后,会出现一个搜索按钮。

    // Use memory adapter for testing to avoid having to deal with an existing database
    const db = new PouchDB('my_database', {
      adapter: 'memory'
    });
    // lunr 
    var searchIndex;
    var loaded = false; // true once index is ready.
    
    // test doc
    const doc = {
      "_id": "mittens",
      "name": "Mittens",
      "occupation": "kitten",
      "age": 3,
      "hobbies": [
        "playing with balls of yarn",
        "chasing laser pointers",
        "lookin' hella cute"
      ]
    };
    // convenience
    const gel = id => document.getElementById(id);
    
    (() => {
      // ops
      return db.put(doc).then(function(response) {
        // allDocs index is ready. Not true for secondary indexes (map/reduce).  
        return db.allDocs({
          include_docs: true
        });
        // setup lunr
      }).then(function(response) {
        searchIndex = lunr(function() {
          this.ref("_id");
          this.field("name", {
            boost: 10
          });
          for (row in response.rows) {
            temp = {
              "name": response.rows[row].doc["name"],
              "_id": response.rows[row].doc["_id"]
            };
            this.add(temp);
          }
        });
    
        loaded = true;
    
      }).catch(function(err) {
      // display init error.
        gel('header').innerText = 'Error';
        gel('result').innerText = JSON.stringify(err, undefined, 3);
      }).finally(function() {
        // display search button on successful init.
        if (loaded) {
          // enable search button
          gel('search').addEventListener('click', function() {
            search();
          });
          gel('search').classList.remove('hide');
        }
      });
    })();
    
    // search function
    function search() {
      let header, result;
      try {
        result = searchIndex.search("mittens");
        header = "Search result";
      } catch (err) {
        // conflate error object and search result object.
        result = [err];
        header = "Error";
      }
      gel('header').innerText = header;
      gel('result').innerText = JSON.stringify(result[0], undefined, 3);
    }
    .hide {
      display: none
    }
    <html>
    <meta charset="utf-8" />
    <script src="//cdn.jsdelivr.net/npm/pouchdb@7.2.1/dist/pouchdb.min.js"></script>
    <script src="https://github.com/pouchdb/pouchdb/releases/download/7.2.1/pouchdb.memory.min.js"></script>
    <script src="https://unpkg.com/lunr/lunr.js"></script>
    
    <body>
      <button id='search' class='hide' style='margin-bottom: 1em'>
      Search for 'mittens'
      </button>
      <div id='header'></div>
      <pre id='result'></pre>
    </body>

    【讨论】:

    • 当我尝试使用 await db.put 时,我遇到了 Uncaught SyntaxError: await is only valid in async functions and async > generators
    • 那么 Promise 是你的选择
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多