Reputation: 1163
So, I'm doing a rewritte of my first vuejs project to nuxtjs and I'm rewriting all my api calls to be store actions, when I noticed that I cannot return values from them, unless I reject them.
No matter how I try to return a value, return x
or return Promise.resolve(x)
my promise's result is always undefined
I tried the following simple action:
async uselessWait(){
setTimeout(() => {
return ("success"); // and return Promise.resolve("success");
}, 1000)
}
and when calling it the result is always undefined
, although the promise resolves normally
Is that intentional, is it a bug or is it just me?
Upvotes: 0
Views: 980
Reputation: 29071
This will return a resolved Promise
immediately.
Ideally
async uselessWait(){
return setTimeout(() => {
return ("success"); // and return Promise.resolve("success");
}, 1000)
}
But setTimeout
does not return a promise, so you can't do that.
Here' a take on setTimeout that does.
setTimeoutPromise = (fn, delay) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
const ret = fn()
resolve(ret)
} catch (e) {
reject(e)
}
}, delay)
})
}
setTimeoutPromise(() => {
console.log('ok')
}, 1000)
So for your example.
async uselessWait(){
return setTimeoutPromise(() => {
return ("success"); // and return Promise.resolve("success");
}, 1000)
}
Now the async function returns a promise that resolves (or rejects if your callback throws)
You could also await instead of returning.
async uselessWait(){
await setTimeoutPromise(() => {
return ("success"); // and return Promise.resolve("success");
}, 1000)
}
Upvotes: 1