【问题标题】:Force an Asynchronous call to behave Synchronously强制异步调用以同步方式运行
【发布时间】:2016-05-25 19:16:45
【问题描述】:

在我的 React 应用程序中,我试图根据其他三个值计算一个值。我已将所有计算逻辑包含在后端,这是一个我进行异步调用的微服务。我异步尝试获取计算值的函数位于许多同步挂钩的中间。

在 UI 层,我调用了我想要返回最终结果(异步返回)的函数。被调用的函数调用另一个函数,该函数调用另一个函数,该函数返回一个新的 Promise。见以下代码:

// DateUI.js (layer 1)
selectDate(dateField, flight, idx, saved, momentTime, e) {
    if (moment(momentTime).isValid()) {
        if (dateField == "StartDate") {
            // The initial problematic function call, need to set endDate before I continue on
            let endDate = PlanLineActions.calculateFlightEndDate(periodTypeId, numberOfPeriods, momentTimeUnix);

            flight.set("EndDate", endDate);
        }

        this.theNextSyncFunction(..., ..., ...);
    }
}


// DateActions.js (layer 2)
calculateFlightEndDate(periodTypeId, numberOfPeriods, startDate) {
    let plan = new Plan();

    plan.getFlightEndDate(periodTypeId, numberOfPeriods, startDate).then(function(response) {
        // response is JSON: {EndDate: "12/05/2016"}
        response.EndDate;
    }, function(error) {
        log.debug("There was an error calculating the End Date.");
    });
}


// DateClass.js (layer 3)
getFlightEndDate(periodTypeId, numberOfPeriods, startDate) {
    let path = '/path/to/microservice';
    return this.callServer(path, 'GET', {periodTypeId: periodTypeId, numberOfPeriods: numberOfPeriods, startDate: startDate});
}


// ServerLayer.js (layer 4)
callServer(path, method = "GET", query = {}, data, inject) {
    return new Promise((resolve, reject) => {
        super.callServer(uri.toString(),method,data,inject).then((data) => {
            resolve(data);
        }).catch((data) => {
            if (data.status === 401) {
                AppActions.doRefresh();
            }
            reject(data);
        });
    });
}

我的印象是,因为 ServerLayer.js(第 4 层)返回一个 new Promise(因此 DateClass.js(第 3 层)),所以调用 plan.getFlightEndDate(...).then(function(response) {... 在响应返回解决或拒绝之前不会完成.这目前没有发生,因为 DateUI.js(第 1 层)中的代码将继续调用 this.theNextSyncFunction,然后在大约 50 毫秒后使用正确的数据解析。

如何在继续使用 selectDate() 之前强制 DateUI.js(第 1 层)中的 PlanLineActions.calculateFlightEndDate(...) 完成响应?

【问题讨论】:

  • 那些是一些疯狂的函数签名。我会考虑使用一个对象。解构对此非常有用。
  • @azium 那将是梦想。不幸的是,上面提供的代码削减了大约 75% 的当前逻辑(正如我们所说,应用程序正在重新设计),并且所有这些单独的签名(假设您正在谈论函数参数)目前都需要明确列出.如果它们包含在一个对象中,则链中的每个钩子都必须对该对象进行解构和重组,这可能会出现性能问题(但肯定会出现可读性问题)。
  • 我不确定你所说的重组是什么意思。你正在做 React 所以也许你遇到过看起来像 let App = ({ someProps }) => <div>... 的组件如果你有性能问题我会非常惊讶。 Ajax 调用显然是您的瓶颈。

标签: javascript asynchronous reactjs microservices


【解决方案1】:

如果某些东西像 ajax 调用一样超出了事件循环,则不能强制它同步。您将需要如下所示的东西:

PlanLineActions.calculateFlightEndDate(periodTypeId, numberOfPeriods, momentTimeUnix)
  .then(endDate => {
    this.theNextSyncFunction(..., ..., ...);
  })

为了做到这一点,calculateFlightEndDate 还需要返回一个 Promise,因此 Promise 可链接是一件好事。

calculateFlightEndDate(periodTypeId, numberOfPeriods, startDate) {
  let plan = new Plan();

  // return promise!
  return plan.getFlightEndDate(periodTypeId, numberOfPeriods, startDate).then(response => {
    return response.EndDate; // must return here
  }, error => {
    log.debug("There was an error calculating the End Date.");
  });
}

应该这样做......还有一件事:你在服务器调用中加倍了承诺。如果某些东西有.then,它已经是一个承诺,所以你可以直接返回它。无需包装new Promise(承诺中的承诺......不需要!)

callServer(path, method = "GET", query = {}, data, inject) {
  // just return!
  return super.callServer(uri.toString(),method,data,inject).then((data) => {
    return data;
  }).catch((data) => {
    if (data.status === 401) {
      AppActions.doRefresh();
    }
    throw data; // throw instead of reject
  });
}

【讨论】:

  • 非常感谢您的解释,这解决了。我从没想过将其余的 selectDate() 逻辑带入 then() 成功后,我认为我必须强制它停止并完成(即使我知道这与 async 所代表的一切背道而驰)才能继续用函数。
  • 一个关于返回语句的问题虽然......当函数有return ...() { return data时,这非常令人困惑。是不是说,当我调用calculateFlightEndDate 时,它会返回一个作为其自身实体存在的承诺,其中包含return 语句?
  • new Promise 和您传递给 then 的回调函数都返回承诺。您最初需要返回承诺以在其他地方使用它......并且您需要在回调函数中返回值,以便它在then 中显示为参数。这就是为什么.then 可以链接ajax().then().then().then()
  • 好笑,这篇文章在一年前发布的时候就看到了,但是还没有像现在这样消费的经验。感谢您在这个问题中提供的 cmets,您对 @azium 的帮助非常大。
【解决方案2】:

我认为你不明白 Promise 是如何工作的。

首先,函数总是立即返回,所以你永远不会阻塞下一行代码的执行(flight.settheNextSyncFunction() 在你的例子中)。这就是返回 Promise 的意义:您会立即获得一个 Promise,您可以将回调附加到(使用then()),该回调将在稍后被调用。如果您希望代码等待承诺解决,您必须将其放入then() 回调中。

其次,您的calculateFlightEndDate()根本不返回任何内容,因此endDate = calculateFlightEndDate() 只是将endDate 设置为undefined

解决方案

您应该从calculateFlightEndDate() 返回一个承诺,然后将您要执行的代码放入then() 回调中:

calculateFlightEndDate(periodTypeId, numberOfPeriods, startDate) {
    let plan = new Plan();

    return plan.getFlightEndDate(periodTypeId, numberOfPeriods, startDate).then((response) => {
        // response is JSON: {EndDate: "12/05/2016"}
        return response.EndDate;
    }, (error) => {
        log.debug("There was an error calculating the End Date.");
    });
}

if (moment(momentTime).isValid()) {
    if (dateField == "StartDate") {
        PlanLineActions.calculateFlightEndDate(periodTypeId, numberOfPeriods, momentTimeUnix).then((endDate) => {
            flight.set("EndDate", endDate);
            this.theNextSyncFunction(...);
        });
    }
}

您还可以考虑使用ES7 async and await,它允许您编写您的异步代码,使其看起来同步,但在后台使用承诺来完成相同的操作东西。

【讨论】:

  • 非常感谢您的回复。你对我对承诺的误解是对的。我希望 .then() 在继续整个链之前等待并完成,但它只是等待完成 .then(func(success) {... 区域的内部
  • 我认为你应该放弃双倍的承诺!
  • 这很公平,包装承诺在这里没有做任何事情。编辑了它。
猜你喜欢
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2011-10-14
相关资源
最近更新 更多