如何在 JavaScript 中同步 API 响应?

发布于 2024-08-20 14:28:29 字数 214 浏览 4 评论 0原文

在 JavaScript 中,需要从两个 API 调用检索数据并使用这两个 API 来处理显示数据。

例如;一个调用返回带有用户 ID 的任务,另一个调用返回用户 ID 和名称的列表。在屏幕上显示之前,我想处理用户 ID,以便根据任务数据显示用户名。

(我能想到的最好的办法是每个响应都有一个标志(完成后设置为 true),由其他调用检查。这样只有最后一个调用才会继续构建页面)。

In JavaScript, have a need to retrieve data from two API calls and use both to process data for the display.

For example; one call returns tasks with a user id, the other returns a list of user id's and names. Before I display onscreen I want to process the user ids so that the user name is shown against the task data.

(The best I can think of is a flag for each response (set to true when done)which is checked by the other call(s). So that only the last call would proceed to build the page).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

娇纵 2024-08-27 14:28:29

这是一个存根,因为它不处理故障,但提供了基本流程。由于您不知道哪个会先返回,因此将它们都关闭并在两者都传送了数据后执行某些操作。

这假设您有某种回调,可以自定义在 api 完成请求时调用。

var apiData = {
  data1: null,
  data2: null
};

function callApis() {
  API.call1({ onComplete: function(result) {
    apiData.data1 = result;
    completeApiRequest();
  }});

  API.call2({ onComplete: function(result) {
    apiData.data2 = result;
    completeApiRequest();
  }});
}

function completeApiRequest() {
  if (apiData.data1 && apiData.data2) {
    doStuff();
  }
}

callApis();

This is a bit of a stub since it doesn't handle failures, but provides a basic flow. Since you don't know which will return first, fire them both off and do something when both have delivered data.

And this assumes that you have some sort of callback that you can customize to call when your api completes a request.

var apiData = {
  data1: null,
  data2: null
};

function callApis() {
  API.call1({ onComplete: function(result) {
    apiData.data1 = result;
    completeApiRequest();
  }});

  API.call2({ onComplete: function(result) {
    apiData.data2 = result;
    completeApiRequest();
  }});
}

function completeApiRequest() {
  if (apiData.data1 && apiData.data2) {
    doStuff();
  }
}

callApis();
旧夏天 2024-08-27 14:28:29

我认为旗帜可能是最好的。或者,如果您想强制执行一系列请求,您可以执行同步 AJAX 调用(当然是 SJAX!)。当然,这将阻止脚本的其余部分执行,直到第一个脚本完成,然后第二个脚本完成。

I think flags are probably your best. Or, you could do synchronous AJAX calls (then it'd be SJAX of course!) if you want to enforce a sequence of requests. Of course, this will block the remainder of your script from executing until first one and then the second have finished.

亚希 2024-08-27 14:28:29

我想你已经差不多了。也许使用具有三种状态的小型状态机,noResponse、oneResponse 和 BothResponses(隐含),大致如下:

var state = "noResponse";
callOne.onresponse = callTwo.onresponse = function() {
  switch(state) {
  case "noResponse":
    state = "oneResponse";
    break;
  case "oneResponse":
    processBothResponses();
    break;
  }
}

我假设您需要的所有数据都在您的两个调用对象中,您可以检查它们并进行交叉检查在 processBothResponses() 中。

I think you're pretty much there already. Maybe use a tiny state machine with three states, noResponse, oneResponse and bothResponses (implied), something along the lines of:

var state = "noResponse";
callOne.onresponse = callTwo.onresponse = function() {
  switch(state) {
  case "noResponse":
    state = "oneResponse";
    break;
  case "oneResponse":
    processBothResponses();
    break;
  }
}

I assume that all the data you need is in your two call objects, and you can examine them and do your cross checking in processBothResponses().

浮光之海 2024-08-27 14:28:29

如果您使用 AJAX 调用,我会将依赖于第一组数据的(第二个)调用放入第一个调用的回调处理程序中:

使用 jQuery:

jQuery.ajax({
   url: url, /* first call */
   data: myData,
   cache: false,
   success: function(data) {
               /* ... processing code ... */
               jQuery.ajax({
                  url: url, /* second call */
                  data: someMoreData,
                  cache: false,
                  success: function(data) {
                           /* ... processing code ... */
                           }
               });
            }
});

这是另一个并行执行此操作的解决方案:

var requestOneCompleted = false;
var requestTwoCompleted = false;

jQuery.ajax({
   url: url, /* first call */
   data: myData,
   cache: false,
   success: function(data) {
               /* ... processing code ... */
               requestOneCompleted = true;
            }
});

jQuery.ajax({
   url: url, /* second call */
   data: someMoreData,
   cache: false,
   success: function(data) {
               /* ... processing code ... */
               requestTwoCompleted = true;
            }
});

setInterval(function() {
   if(requestOneCompleted && requestTwoCompleted) {
      doStuffWithData();
   }
}, 250);

注意我还没有测试过这个。

If you're using an AJAX call, I'd put the (second) call that depends on the first set of data, into the callback handler of the first call:

Using jQuery:

jQuery.ajax({
   url: url, /* first call */
   data: myData,
   cache: false,
   success: function(data) {
               /* ... processing code ... */
               jQuery.ajax({
                  url: url, /* second call */
                  data: someMoreData,
                  cache: false,
                  success: function(data) {
                           /* ... processing code ... */
                           }
               });
            }
});

Here's another solution that does it in parallel:

var requestOneCompleted = false;
var requestTwoCompleted = false;

jQuery.ajax({
   url: url, /* first call */
   data: myData,
   cache: false,
   success: function(data) {
               /* ... processing code ... */
               requestOneCompleted = true;
            }
});

jQuery.ajax({
   url: url, /* second call */
   data: someMoreData,
   cache: false,
   success: function(data) {
               /* ... processing code ... */
               requestTwoCompleted = true;
            }
});

setInterval(function() {
   if(requestOneCompleted && requestTwoCompleted) {
      doStuffWithData();
   }
}, 250);

Note I haven't tested this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文