admin管理员组

文章数量:1331667

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?

Share asked Jul 21, 2018 at 4:47 UkashaUkasha 2,3343 gold badges23 silver badges30 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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!!!");

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