admin管理员组文章数量:1330385
You can see what I've done here.
import "babel-polyfill";
import React from "react";
import ReactDOM from "react-dom";
const asyncFunc = () => {
return new Promise(resolve => {
setTimeout(resolve("Gotcha!!!"), 10000);
});
};
class App extends React.Component {
state = {
text: "Fetching..."
};
ponentDidMount = async () => {
const text = await asyncFunc();
this.setState({ text });
};
render() {
return <div className="App">{this.state.text}</div>;
}
}
The app should show Fetching...
first, then shows Gotcha!!!
after 10 seconds. But, it's not working. What's my mistake?
You can see what I've done here.
import "babel-polyfill";
import React from "react";
import ReactDOM from "react-dom";
const asyncFunc = () => {
return new Promise(resolve => {
setTimeout(resolve("Gotcha!!!"), 10000);
});
};
class App extends React.Component {
state = {
text: "Fetching..."
};
ponentDidMount = async () => {
const text = await asyncFunc();
this.setState({ text });
};
render() {
return <div className="App">{this.state.text}</div>;
}
}
The app should show Fetching...
first, then shows Gotcha!!!
after 10 seconds. But, it's not working. What's my mistake?
3 Answers
Reset to default 5The problem is:
setTimeout(resolve("Gotcha!!!"), 10000);
The first argument to setTimeout
should be a function. At the moment, you're calling resolve
immediately as setTimeout
tries to resolve its arguments (synchronously). Instead, pass it a function that then calls resolve
:
setTimeout(() => resolve("Gotcha!!!"), 10000);
or
setTimeout(resolve, 10000, "Gotcha!!!");
You need to pass setTimeout
a callback function, change it to this
setTimeout(() => resolve("Gotcha!!!"), 10000);
import "babel-polyfill";
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const asyncFunc = () => {
return new Promise(resolve => {
setTimeout(() => resolve("Gotcha!!!"), 10000);
});
};
class App extends React.Component {
constructor() {
super();
this.state = {
text: "Fetching..."
};
}
ponentDidMount = async () => {
const newText = await asyncFunc();
this.setState({ text: newText });
};
render() {
return <div className="App">{this.state.text}</div>;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
本文标签: javascriptAsync await and setTimeout are not working in ReactJSStack Overflow
版权声明:本文标题:javascript - Async await and setTimeout are not working in ReactJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742266008a2443405.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论