I have a quick question about two different implementations of code in a react native app. I'd like to know if and why one is considered better than the other and why.
#1 uses a standard setTimeout
within componentDidMount()
like so:
componentDidMount() {
setTimeout(() => {
this.setState({ editable: true });
}, 2000);
}
The second one also involves waiting, but looks like this:
const wait = (timeout) => {
return new Promise(resolve => setTimeout(resolve, timeout));
}
componentDidMount() {
wait(2000).then(() => {
this.setState({ editable: true });
});
}
Does the second implementation do something the first does not? Is one more robust than the other?
CodePudding user response:
Considering your first question
Does the second implementation do something the first does not?
Besides promise being faster, Both are exactly the same.
Is one more robust than the other?
the second one is more common in a lot of frameworks and libraries as it provides a better way of chaining with a nice way of catch
ing errors
for more info Promise vs setTimeout
for example
in react-testing-library
there is waitForElementToBeRemoved