1

我有一个箭头函数,它被调用cDM以每 20 秒使用setTimeout(). 该setTimeout()方法永远不会像它应该的那样向服务器发出另一个请求。所以我认为代码永远不会到达。我不确定如何修改它以便达到该方法。

componentDidMount() {
    //get request to /schedules
    //update state with response data
    this.getUpdatedStatus();
}

  getUpdatedStatus = () => {
    //fetch updated status,
    //list of arrays that are updated to state in `cDM`
    const schedules = this.state.schedules;
    Promise.all(
      schedules
        .map(schedule =>
          axios({
            method: "get",
            url: schedule.selfUri,
            headers: {
              Accept: " someValue"
            }
          })
        )
        .then(response => {
          if (response.data.data[0].status !== "Complete") {
            this.timeout = setTimeout(() => this.getUpdatedStatus(), 20000);
          }
          console.log(response);
          this.setState(
            {
              scheduleStatus: response.data.data[0].status,
            },
            () => {
              console.log(this.state.scheduleStatus);
            }
          );
        })
    ).catch(error => console.log(error.response));
  };

代码沙盒

4

2 回答 2

1

简而言之,您使用了错误的 the Promise.all(),这是因为结构类似于:

Promise.all([p1, p2,...,pn]).then([r1, r2, ..., rn])

但你的代码是这样的: Promise.all([p1, p2,...,pn].then(r))

所以基本上你的 promise.all 应该改为这样的:

  getUpdatedStatus = () => {
    //fetch updated status,
    //list of arrays that are updated to state in `cDM`
    const schedules = this.state.schedules;
    Promise.all(
      schedules
        .map(schedule =>
          axios({
            method: "get",
            url: schedule.selfUri,
            headers: {
              Accept: " someValue"
            }
          })
        ))
        .then(responses => {
          //now you have to iterate over the responses
          const isIncomplete = responses.some(r => r.data.data[0].status !== "Complete")
          if (isIncomplete) {
            this.timeout = setTimeout(() => this.getUpdatedStatus(), 20000);
          }
          console.log(responses);
          this.setState(
            {
              scheduleStatus: isIncomplete?'Pending':'Complete',//improve this piece of code
            },
            () => {
              console.log(this.state.scheduleStatus);
            }
          );
        })
  };

在这里,您有一个工作沙箱,其中包含您在沙箱中提供的代码。

于 2018-12-07T17:28:45.053 回答
0

好吧,基本上@PrinceHernandez 找到了主要问题,但是您的代码还有很多其他问题:

  • 输入字段是只读的
  • 失踪tbody
  • key每个属性都缺失tr

我冒昧地在这里进行了润色:https ://codesandbox.io/s/6vyk48x18n

打开控制台,你会看到代码每打印 2s 更新一次1。将 thenable 移动到每个调度都需要有一个标志来控制每个getUpdatedStatus.

于 2018-12-07T17:44:20.740 回答