【发布时间】: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