Reputation: 52
I've been trying to understand how async/await works, all I want to do is have it wait until the value is returned. However, I could not get it to do so with callbacks nor promises nor async/await
. What am I doing wrong, and why does async/await
not work as I expect it to? (wait with running other code until this promise is resolved)
Many questions like this one link to "introduction pages". I've read them all, I understand what they do, I just don't know how to properly write them out, as I believe I did everything correctly, I'm just missing something
console.log("xcdcxcxcxccxvccvffdgfcd")
;
thing();
async function thing() {
let c = await otherthing();
console.log("dfasfadsfdasasdfa" + c)
}
async function otherthing() {
await setTimeout(function() {
return new Promise((resolve, reject) => {
let f = "rerewwqfewfasgsadf"
return resolve(f);
})
}, 3000);
}
console.log
is supposed to wait until the promised value c
is returned, however, it does not seem to work. Why?
Upvotes: 1
Views: 137
Reputation: 20236
Async/await works with functions that return promises. Your otherthing
function doesn't return anything.
You can fix the code by returning the promise you are instantiating, like this:
thing();
async function thing() {
let c = await otherthing();
console.log("dfasfadsfdasasdfa" + c)
}
function otherthing() {
return new Promise((resolve, reject) => {
setTimeout(function () {
let f = "rerewwqfewfasgsadf"
resolve(f);
}, 3000)
});
}
Upvotes: 4
Reputation: 664395
You must return
the new Promise
from the otherthing
function, not from the setTimeout
callback. You are supposed to construct the promise, in its executor callback start the asynchronous action (setTimeout
) and then asynchronously resolve()
or reject()
the promise.
function otherthing() {
return new Promise((resolve, reject) => {
setTimeout(function(){
let f = "rerewwqfewfasgsadf"
resolve(f);
}, 3000);
});
}
You don't need any async
/await
here for the function that is essentially only a promise wrapper around setTimeout
. See also How do I convert an existing callback API to promises?.
Upvotes: 3
Reputation: 6850
You should move setTimeout
inside Promise
body and there do resolve(f)
function otherthing() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let f = "rerewwqfewfasgsadf"
resolve(f);
}, 3000);
});
}
Upvotes: 2
Reputation: 943220
async function otherthing
has no return
statement, so it will always return a promise that resolves to undefined
.
await setTimeout(...)
doesn't make any sense. You can only await
a promise, and setTimeout
does not return a promise.
You need to explicitly:
new Promise()
inside otherthing
resolve()
it with the desired value inside the callback function you pass to setTimeout
return
the promise from otherthing
Don't create a promise inside the callback function you pass to setTimeout
. It is pointless there.
Upvotes: 0