javascript - 异步/等待函数不等待承诺结束
问题描述
let myObject = ( () => {
let run = async() => {
foo = new genericFunction();
status = await foo.myFunction();
}
})();
另一个 FIle.js
let genericFunction = function() {
this.getData = async () => {
$.getJSON("path/to/file.json", function (data) {
console.log("Apple", data.name);
return data.name;
}).fail(function(jqxhr, textStatus, error){
console.log("Loading Error :: ", error);
)};
}
this.myFunction = async () => {
let data = this.getData();
console.log('DATAA:::', data); //This should be the first output
}
}
问题是:
status
总是= undefined
因为它在执行之前以某种方式返回getJSON
,我不知道为什么。
解决方案
另一个 FIle.js应该是这样的:
let genericFunction = function() {
this.getData = async () => {
var result = await $.getJSON("path/to/file.json", function (data) {
console.log("Apple", data.name);
return data.name;
}).catch(function(jqxhr, textStatus, error){
console.log("Loading Error :: ", error);
)};
return result;
}
this.myFunction = async () => {
let data = this.getData();
console.log('DATAA:::', data); //This should be the first output
}
}
推荐阅读
- jquery - 设置没有值的选择列表项的值会中断提交事件处理程序
- rust - Cargo 生态系统中的“箱子”到底是什么?与 crates.io 上的内容的映射是什么?
- android - 使用adjustresize时如何隐藏导航栏和全屏?
- forms - 使用令牌形成 Click()
- python - 未捕获 asyncio.CancelledError
- c# - OxyPlot 触发 LineSeries 颜色变化通知
- python - MQTT 和 Python - 继续发送消息
- javascript - 在 Angular 6 中找不到名称
- python - 如何从 Azure Databricks Spark 中的 DataFrame 获取特定的行和列
- javascript - 更改文本区域字体系列的功能(使用选项选择)