JavaScript如何等待功能及其所有子功能完成

在我的reactJS应用程序中,我有一个带有onClick的以下按钮

<Button
  onClick={() => {
    this.authenticateUser(this.state.user, this.state.password)
      .then(user => {
        if (user === "true") {
          this.setState({ markAsDone: true }, () => {
            this.startStepInstancePostConditions(this.props.step, this.props.instance.id);
            this.markSepInstanceAsDone(this.props.step, this.props.instance.id);
          });
          this.toggleDialog();
        }
      })
      .catch(() => {
        this.snackBarHandler(this.toggleSnackBar, "", t("auditLogs:newAuditLog.error"), 5000);
      });
  }}
>
  {t("processes:processStepInstances.markAsDoneDialog.save")}
</Button>

我不确定如何解决我的问题.

两个功能:

this.startStepInstancePostConditions(this.props.step,this.props.instance.id);  

this.markSepInstanceAsDone(this.props.step,this.props.instance.id);

遍历一些数组并执行一些axios帖子.

我希望我的应用程序调用此命令:

 this.props.history.push("/processes/processInstance/" + this.props.instance.id);

如果以上两个功能和所有子功能均已完成.我该如何实现?

提前致谢

更新:

export function markSepInstanceAsDone(step, processInstanceId) {
    const user = sessionStorage.getItem("username");
    const clientId = sessionStorage.getItem("client");
    axios.post(PROCESS_INSTANCES_URL + '/markProcessStepInstanceAsDone/' + clientId, {
        stepInstanceId: step.id,
        user: user,
        comment: this.state.markStepInstanceAsDoneComment
    })
        .then((response) => {
            this.getContentComponentPostConditions(step, processInstanceId);
            this.props.history.push("/processes/processInstance/" + processInstanceId);
        })
        .catch((error) => {
            this.setState({dialogLoaded: false});
            console.log(error);
        });
}

更新资料

export function startStepInstancePostConditions(step,processInstanceID) {
    step.postConditions.map(postConditionTemplate => {
        axios.get(API_URL + '/processStepTemplates/' + postConditionTemplate.id)
            .then(response => {
                this.createProcessInstanceAutomatic(postConditionTemplate, response.data);
            })
            .catch(error => {
                console.log(error);
            });
    });
}

解决方法:

让两个函数都从其axios调用返回promise,然后可以使用Promise.all等到两个函数都完成后再执行某些操作.

startStepInstancePostConditions() {
  return axios.post('...')
}
markSepInstanceAsDone() {
  return axios.post('...')
}

// inside the authenticateUser callback
Promise.all([
  this.startStepInstancePostConditions(this.props.step, this.props.instance.id),
  this.markSepInstanceAsDone(this.props.step, this.props.instance.id)
]).then(() => {
  this.props.history.push("/processes/processInstance/" + this.props.instance.id)
})
上一篇:javascript-对象无效,作为React子反应错误?


下一篇:javascript-当用户移至下一个链接时,如何突出显示上一个链接?