gpt4 book ai didi

javascript - 无法从 'async' 函数获取返回值 - Javascript

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:57:06 25 4
gpt4 key购买 nike

我正在使用 javascript 中的一些异步函数,但我遇到了一个问题,我已经发布了 here但这对每个人来说都是一种不切实际的体验。现在,我做了一个简单的构造函数,里面有相同的成员函数并返回了一个值,但对我来说似乎是同样的问题,我尽力了但我不知道问题是什么,如果你运行这段代码然后你可以检查我想要的是。这是 demo link在 JSfiddle 上,您可以在 console 上看到结果。

这是我的代码

function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;

async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
let p = new Promise(function(res, rej) {
setTimeout(async function() {
if (count === 2) {
res({
page_job_details: "khan"
});
} else {
count++;
waitMore();
}
}, 2000);
});
var res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
waitMore();
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
return khan;
}
}
new Test().init().then(function(res) {
console.log(res);
})

When you comment out the conditions within the setTimeout() and simply res({page_job_details:"khan"}); then you'll get the results in the new Test().init().then(function(res){ console.log(res); }). Otherwise not, and that's the main problem.

最佳答案

其中一个问题是您没有从 promise 中返回递归调用的结果。

不只是递归地调用它

waitMore();

您似乎期望递归调用的结果沿着管道返回

res(waitMore());

function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;

async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
let p = new Promise(function(res, rej) {
setTimeout(async function() {
if (count === 2) {
res({
page_job_details: "khan"
});
} else {
count++;
res(waitMore());
}
}, 2000);
});
var res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
waitMore();
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
return khan;
}
}
new Test().init().then(function(res) {
console.log(res);
})

关于javascript - 无法从 'async' 函数获取返回值 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53441475/

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