I am working with some asynchronous functions in javascript, but I am facing a problem, that I already posted here but that was a bit unpractical experience for everyone. Now, I made a simple constructor function with same member functions inside and returned a value, but seems like same problem to me, I tried my best but I don't know what is the problem, if you run this code then You can check what I want. Here's the demo link on JSfiddle, where you can see the results on console.
This is my Code
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 simplyres({page_job_details:"khan"});then you'll get the results in thenew Test().init().then(function(res){ console.log(res); }). Otherwise not, and that's the main problem.
res, when theTest().init()is called..init().thensectioninit()@MiguelAngel