Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async await and setTimeout are not working in ReactJS

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..."
  };

  componentDidMount = 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?

like image 939
Ukasha Avatar asked Feb 17 '26 04:02

Ukasha


1 Answers

The 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!!!");
like image 124
CertainPerformance Avatar answered Feb 18 '26 20:02

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!