Can't get returned value from an 'async' function - Javascript
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.
javascript
add a comment |
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.
javascript
Thanks, can you explain what sort of output you were expecting instead?
– CertainPerformance
Nov 23 '18 at 6:17
@CertainPerformance I am expecting the answer in theres
, when theTest().init()
is called.
– Nadeem Ahmad
Nov 23 '18 at 6:18
You're receiving "khan" at the end of the promise, is not what you want?
– Miguel Angel
Nov 23 '18 at 6:20
@MiguelAngel It's not being chained to the end.init().then
section
– CertainPerformance
Nov 23 '18 at 6:22
I want the results returned by theinit()
@MiguelAngel
– Nadeem Ahmad
Nov 23 '18 at 6:22
add a comment |
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.
javascript
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.
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);
})
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);
})
javascript
javascript
edited Nov 23 '18 at 6:21
Nadeem Ahmad
asked Nov 23 '18 at 6:15
Nadeem AhmadNadeem Ahmad
888
888
Thanks, can you explain what sort of output you were expecting instead?
– CertainPerformance
Nov 23 '18 at 6:17
@CertainPerformance I am expecting the answer in theres
, when theTest().init()
is called.
– Nadeem Ahmad
Nov 23 '18 at 6:18
You're receiving "khan" at the end of the promise, is not what you want?
– Miguel Angel
Nov 23 '18 at 6:20
@MiguelAngel It's not being chained to the end.init().then
section
– CertainPerformance
Nov 23 '18 at 6:22
I want the results returned by theinit()
@MiguelAngel
– Nadeem Ahmad
Nov 23 '18 at 6:22
add a comment |
Thanks, can you explain what sort of output you were expecting instead?
– CertainPerformance
Nov 23 '18 at 6:17
@CertainPerformance I am expecting the answer in theres
, when theTest().init()
is called.
– Nadeem Ahmad
Nov 23 '18 at 6:18
You're receiving "khan" at the end of the promise, is not what you want?
– Miguel Angel
Nov 23 '18 at 6:20
@MiguelAngel It's not being chained to the end.init().then
section
– CertainPerformance
Nov 23 '18 at 6:22
I want the results returned by theinit()
@MiguelAngel
– Nadeem Ahmad
Nov 23 '18 at 6:22
Thanks, can you explain what sort of output you were expecting instead?
– CertainPerformance
Nov 23 '18 at 6:17
Thanks, can you explain what sort of output you were expecting instead?
– CertainPerformance
Nov 23 '18 at 6:17
@CertainPerformance I am expecting the answer in the
res
, when the Test().init()
is called.– Nadeem Ahmad
Nov 23 '18 at 6:18
@CertainPerformance I am expecting the answer in the
res
, when the Test().init()
is called.– Nadeem Ahmad
Nov 23 '18 at 6:18
You're receiving "khan" at the end of the promise, is not what you want?
– Miguel Angel
Nov 23 '18 at 6:20
You're receiving "khan" at the end of the promise, is not what you want?
– Miguel Angel
Nov 23 '18 at 6:20
@MiguelAngel It's not being chained to the end
.init().then
section– CertainPerformance
Nov 23 '18 at 6:22
@MiguelAngel It's not being chained to the end
.init().then
section– CertainPerformance
Nov 23 '18 at 6:22
I want the results returned by the
init()
@MiguelAngel– Nadeem Ahmad
Nov 23 '18 at 6:22
I want the results returned by the
init()
@MiguelAngel– Nadeem Ahmad
Nov 23 '18 at 6:22
add a comment |
2 Answers
2
active
oldest
votes
One of the issues is that you are not returning the result of the recursive call from within the promise.
Instead of just calling it recursively
waitMore();
you seem to expect the result of the recursive call to be returned down the pipeline
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);
})
Perfect Results, can you explain it a bit to me technically; why the results ofconsole.log("Response is : " + res.page_job_details);
is three times displayed ? in theelse
part .
– Nadeem Ahmad
Nov 23 '18 at 6:31
1
Three seems to be the level of your recursion.
– Wiktor Zychla
Nov 23 '18 at 6:33
add a comment |
There are two issues:
Inside
waitMore
'ssetTimeout
,res
is only called ifcount === 2
. Otherwise, the created promise never resolves, and whatever might beawait
ingwaitMore()
will never resolve - instead, that thread will remain suspended forever. You can fix this by callingres
regardless of whethercount
is2
or not - if thecount
is less than2
, callres
with another invocation ofwaitMore
:
res(waitMore());
On the level of the
this.init
function, in the case that you need to wait more, you need toawait waitMore()
(and put the response in a new variable that gets returned) so as to chain the Promise properly:
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
}
function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;
async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
const p = new Promise((res, rej) => {
setTimeout(() => {
if (count === 2) res({ page_job_details: "khan" });
else {
count++;
res(waitMore());
}
}, 2000);
});
const res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
console.log('about to return from init')
return khan;
}
}
new Test().init().then(function(res) {
console.log('in init callback')
console.log(res);
})
Perfect, Thank you for your answer !
– Nadeem Ahmad
Nov 23 '18 at 6:34
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53441475%2fcant-get-returned-value-from-an-async-function-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
One of the issues is that you are not returning the result of the recursive call from within the promise.
Instead of just calling it recursively
waitMore();
you seem to expect the result of the recursive call to be returned down the pipeline
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);
})
Perfect Results, can you explain it a bit to me technically; why the results ofconsole.log("Response is : " + res.page_job_details);
is three times displayed ? in theelse
part .
– Nadeem Ahmad
Nov 23 '18 at 6:31
1
Three seems to be the level of your recursion.
– Wiktor Zychla
Nov 23 '18 at 6:33
add a comment |
One of the issues is that you are not returning the result of the recursive call from within the promise.
Instead of just calling it recursively
waitMore();
you seem to expect the result of the recursive call to be returned down the pipeline
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);
})
Perfect Results, can you explain it a bit to me technically; why the results ofconsole.log("Response is : " + res.page_job_details);
is three times displayed ? in theelse
part .
– Nadeem Ahmad
Nov 23 '18 at 6:31
1
Three seems to be the level of your recursion.
– Wiktor Zychla
Nov 23 '18 at 6:33
add a comment |
One of the issues is that you are not returning the result of the recursive call from within the promise.
Instead of just calling it recursively
waitMore();
you seem to expect the result of the recursive call to be returned down the pipeline
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);
})
One of the issues is that you are not returning the result of the recursive call from within the promise.
Instead of just calling it recursively
waitMore();
you seem to expect the result of the recursive call to be returned down the pipeline
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);
})
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);
})
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);
})
answered Nov 23 '18 at 6:27
Wiktor ZychlaWiktor Zychla
39.6k55680
39.6k55680
Perfect Results, can you explain it a bit to me technically; why the results ofconsole.log("Response is : " + res.page_job_details);
is three times displayed ? in theelse
part .
– Nadeem Ahmad
Nov 23 '18 at 6:31
1
Three seems to be the level of your recursion.
– Wiktor Zychla
Nov 23 '18 at 6:33
add a comment |
Perfect Results, can you explain it a bit to me technically; why the results ofconsole.log("Response is : " + res.page_job_details);
is three times displayed ? in theelse
part .
– Nadeem Ahmad
Nov 23 '18 at 6:31
1
Three seems to be the level of your recursion.
– Wiktor Zychla
Nov 23 '18 at 6:33
Perfect Results, can you explain it a bit to me technically; why the results of
console.log("Response is : " + res.page_job_details);
is three times displayed ? in the else
part .– Nadeem Ahmad
Nov 23 '18 at 6:31
Perfect Results, can you explain it a bit to me technically; why the results of
console.log("Response is : " + res.page_job_details);
is three times displayed ? in the else
part .– Nadeem Ahmad
Nov 23 '18 at 6:31
1
1
Three seems to be the level of your recursion.
– Wiktor Zychla
Nov 23 '18 at 6:33
Three seems to be the level of your recursion.
– Wiktor Zychla
Nov 23 '18 at 6:33
add a comment |
There are two issues:
Inside
waitMore
'ssetTimeout
,res
is only called ifcount === 2
. Otherwise, the created promise never resolves, and whatever might beawait
ingwaitMore()
will never resolve - instead, that thread will remain suspended forever. You can fix this by callingres
regardless of whethercount
is2
or not - if thecount
is less than2
, callres
with another invocation ofwaitMore
:
res(waitMore());
On the level of the
this.init
function, in the case that you need to wait more, you need toawait waitMore()
(and put the response in a new variable that gets returned) so as to chain the Promise properly:
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
}
function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;
async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
const p = new Promise((res, rej) => {
setTimeout(() => {
if (count === 2) res({ page_job_details: "khan" });
else {
count++;
res(waitMore());
}
}, 2000);
});
const res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
console.log('about to return from init')
return khan;
}
}
new Test().init().then(function(res) {
console.log('in init callback')
console.log(res);
})
Perfect, Thank you for your answer !
– Nadeem Ahmad
Nov 23 '18 at 6:34
add a comment |
There are two issues:
Inside
waitMore
'ssetTimeout
,res
is only called ifcount === 2
. Otherwise, the created promise never resolves, and whatever might beawait
ingwaitMore()
will never resolve - instead, that thread will remain suspended forever. You can fix this by callingres
regardless of whethercount
is2
or not - if thecount
is less than2
, callres
with another invocation ofwaitMore
:
res(waitMore());
On the level of the
this.init
function, in the case that you need to wait more, you need toawait waitMore()
(and put the response in a new variable that gets returned) so as to chain the Promise properly:
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
}
function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;
async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
const p = new Promise((res, rej) => {
setTimeout(() => {
if (count === 2) res({ page_job_details: "khan" });
else {
count++;
res(waitMore());
}
}, 2000);
});
const res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
console.log('about to return from init')
return khan;
}
}
new Test().init().then(function(res) {
console.log('in init callback')
console.log(res);
})
Perfect, Thank you for your answer !
– Nadeem Ahmad
Nov 23 '18 at 6:34
add a comment |
There are two issues:
Inside
waitMore
'ssetTimeout
,res
is only called ifcount === 2
. Otherwise, the created promise never resolves, and whatever might beawait
ingwaitMore()
will never resolve - instead, that thread will remain suspended forever. You can fix this by callingres
regardless of whethercount
is2
or not - if thecount
is less than2
, callres
with another invocation ofwaitMore
:
res(waitMore());
On the level of the
this.init
function, in the case that you need to wait more, you need toawait waitMore()
(and put the response in a new variable that gets returned) so as to chain the Promise properly:
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
}
function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;
async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
const p = new Promise((res, rej) => {
setTimeout(() => {
if (count === 2) res({ page_job_details: "khan" });
else {
count++;
res(waitMore());
}
}, 2000);
});
const res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
console.log('about to return from init')
return khan;
}
}
new Test().init().then(function(res) {
console.log('in init callback')
console.log(res);
})
There are two issues:
Inside
waitMore
'ssetTimeout
,res
is only called ifcount === 2
. Otherwise, the created promise never resolves, and whatever might beawait
ingwaitMore()
will never resolve - instead, that thread will remain suspended forever. You can fix this by callingres
regardless of whethercount
is2
or not - if thecount
is less than2
, callres
with another invocation ofwaitMore
:
res(waitMore());
On the level of the
this.init
function, in the case that you need to wait more, you need toawait waitMore()
(and put the response in a new variable that gets returned) so as to chain the Promise properly:
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
}
function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;
async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
const p = new Promise((res, rej) => {
setTimeout(() => {
if (count === 2) res({ page_job_details: "khan" });
else {
count++;
res(waitMore());
}
}, 2000);
});
const res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
console.log('about to return from init')
return khan;
}
}
new Test().init().then(function(res) {
console.log('in init callback')
console.log(res);
})
function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;
async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
const p = new Promise((res, rej) => {
setTimeout(() => {
if (count === 2) res({ page_job_details: "khan" });
else {
count++;
res(waitMore());
}
}, 2000);
});
const res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
console.log('about to return from init')
return khan;
}
}
new Test().init().then(function(res) {
console.log('in init callback')
console.log(res);
})
function Test() {
this.init = async function() {
var count = 0,
page_job_details = null;
async function waitMore() {
console.log("Wait more loaded - " + (count + 1) + "...");
const p = new Promise((res, rej) => {
setTimeout(() => {
if (count === 2) res({ page_job_details: "khan" });
else {
count++;
res(waitMore());
}
}, 2000);
});
const res = await p;
if (res.page_job_details === '' || res.page_job_details === 'undefined' || res.page_job_details === null) {
console.log("waiting more...");
const newRes = await waitMore();
return newRes;
} else {
console.log("Response is : " + res.page_job_details);
return res;
}
}
var khan;
await waitMore().then(function(r) {
console.log(r);
khan = r;
});
console.log('about to return from init')
return khan;
}
}
new Test().init().then(function(res) {
console.log('in init callback')
console.log(res);
})
answered Nov 23 '18 at 6:29
CertainPerformanceCertainPerformance
85.7k154371
85.7k154371
Perfect, Thank you for your answer !
– Nadeem Ahmad
Nov 23 '18 at 6:34
add a comment |
Perfect, Thank you for your answer !
– Nadeem Ahmad
Nov 23 '18 at 6:34
Perfect, Thank you for your answer !
– Nadeem Ahmad
Nov 23 '18 at 6:34
Perfect, Thank you for your answer !
– Nadeem Ahmad
Nov 23 '18 at 6:34
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53441475%2fcant-get-returned-value-from-an-async-function-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Thanks, can you explain what sort of output you were expecting instead?
– CertainPerformance
Nov 23 '18 at 6:17
@CertainPerformance I am expecting the answer in the
res
, when theTest().init()
is called.– Nadeem Ahmad
Nov 23 '18 at 6:18
You're receiving "khan" at the end of the promise, is not what you want?
– Miguel Angel
Nov 23 '18 at 6:20
@MiguelAngel It's not being chained to the end
.init().then
section– CertainPerformance
Nov 23 '18 at 6:22
I want the results returned by the
init()
@MiguelAngel– Nadeem Ahmad
Nov 23 '18 at 6:22