【发布时间】:2020-07-18 02:19:08
【问题描述】:
我看到一些异步 Javascript 访问类方法很奇怪。
我有一些 Javascript 可以进行相当密集的搜索,这可能需要一些时间(大约 1 分钟),所以我想异步运行它。
这是我的 MVCE:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body>
<div id="search-form">
<input id="search-terms" type="text" placeholder="enter search terms" />
<button id="search-button">Search</button>
</div>
</body>
<script type="text/javascript">
class Index {
constructor() {
this.internal_hash = {};
}
get_term_count(){
return Object.keys(this.internal_hash).length;
}
do_big_long_expensive_calculation(){
var i=0;
for(i=0; i<10000; i++){
this.internal_hash[i] = i+1;
}
return i;
}
search_text(text){
var results = this.do_big_long_expensive_calculation();
return results;
}
};
var search_index = new Index;
var search_results = null;
$(document).ready(function(){
async function searchIndex(){
let text = $('#search-terms').val();
console.log('searching index for text:'+text);
console.log('using index with terms:'+search_index.get_term_count());
search_results = search_index.search_text(text);
console.log('results:'+search_results.length);
return search_results;
}
$('#search-button').click(function(){
console.log('search button clicked')
var el = $(this);
el.prop("disabled", true);
el.text('Searching...');
searchIndex()
.then(function(){
console.log('search results found:'+(search_results.length));
el.text('Search');
el.prop("disabled", false);
})
.catch(reason => console.log(reason.message));
});
});
</script>
</html>
如果我打电话:
search_index.search_text('sdfssdfsf')
从浏览器的控制台,它返回预期的10000。
但是,如果我单击搜索按钮,console.log 语句将打印出undefined 以获取search_index.search_text 返回的值。
这是为什么?我唯一能想到的是async 有一些我不知道的特征。 async Javascript 是否无法访问与正常同步执行模型相同的内存?
【问题讨论】:
-
添加
return来完成你的异步函数 -
从
searchIndex函数返回search_results -
@fedesc 我正在分配一个全局变量,也没有从 searchIndex 访问返回值。这不应该是必要的,对吧?
-
async-await就是这样工作的。A Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.你必须返回一些东西才能让函数解析。否则你只是得到一个未解决的承诺 -
@fedesc 我尝试返回值。结果相同。
标签: javascript async.js