异步等待和 setTimeout 在 ReactJS 中不起作用

Uka*_*sha 2 javascript async-await reactjs

你可以在这里看到我所做的事情。

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>;
  }
}
Run Code Online (Sandbox Code Playgroud)

应用程序应首先显示,然后在 10 秒后Fetching...显示。Gotcha!!!但是,它不起作用。我有什么错?

Cer*_*nce 5

问题是:

setTimeout(resolve("Gotcha!!!"), 10000);
Run Code Online (Sandbox Code Playgroud)

第一个参数setTimeout应该是一个函数。目前,您正在立即调用 ,尝试解析其参数(同步)。相反,向它传递一个函数,然后调用:resolvesetTimeoutresolve

setTimeout(() => resolve("Gotcha!!!"), 10000);
Run Code Online (Sandbox Code Playgroud)

或者

setTimeout(resolve, 10000, "Gotcha!!!");
Run Code Online (Sandbox Code Playgroud)