这是我在香草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,但是它不起作用。
如何使我的原始脚本等待dbpouch数据库的索引编制?
因为我有一个:
(index):59 Uncaught TypeError: Cannot read property 'search' of undefined
因为我的搜索尚未准备好。我想找到一种使脚本等待搜索索引完成的方法。
当我尝试等待db.put(doc);
我有一个
未捕获的SyntaxError:等待仅在异步函数和异步中有效 发电机
这是一个jsfiddle:
https://jsfiddle.net/bussiere/4p1q3L9j/1/
我的主要目标是将dbpouch加载到月球上,然后可以进行多次搜索。
因此,只需要一次进行lunr搜索,而不是每次我都想进行搜索。
致谢