gpt4 book ai didi

javascript - Async/Await 函数不等待 Promise 结束

转载 作者:行者123 更新时间:2023-12-01 01:22:57 25 4
gpt4 key购买 nike

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
}

}

关于javascript - Async/Await 函数不等待 Promise 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com