Hello!
I am new to async actions in general, but I need to implement them for a react-redux project. To practice redux-thunk, I have been playing with the this code someone posted: [https://codepen.io/sh1zuku/pen/XBrQVr?editors=0010](simple React Redux Thunk example)
On line 69 in the addValueLazy function, I changed the code to:
First, I didn’t think that setTimeout returns a promise. Second all, if it did, then you would need to wrap that second part in an anonymous function:
... .then(() => window.alert("added!"));
otherwise it is just going to evaluate that function. You always pass a function. As you have it, it is evaluating that call and “thenning” the return value, in other words, undefined.
The await (afaik) is only waiting for the setTimeout, in other words, the “setting” - it is not waiting for the callback function. If you want your alert to wait, it needs to be in the callback function being passed to setTimeout.
Right, setTimeout does not return a promise - at least it is throwing an error for me. You could build a promise wrapped version with something like this:
const setTimeoutPromise = (callback, delay) =>
new Promise(resolve => setTimeout(() => resolve(callback()), delay));
console.log("before the promise");
setTimeoutPromise(() => console.log("callback function"), 3000)
.then(() => console.log("then function"));
console.log("after the promise");
The output is this:
before the promise
after the promise
callback function
then function
The first two lines come instantly, the second two after the 3 second delay, exactly what we are expecting.
Thank you so much! My question now is, why is resolve entered twice in the second line? I’m trying to understand the meaning behind the syntax here.
This is what you tested:
new Promise(resolve => setTimeout(() => resolve(callback()), delay));
Is there a reason it wouldn’t be this?:
new Promise(resolve => setTimeout((dispatch) => dispatch(callback()), delay));
…oh! I guess it because resolve was only passed as a parameter and so it needs to be called later and will perform (callback()) when it resolves.