如何在 JavaScript 中同步 API 响应?
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个存根,因为它不处理故障,但提供了基本流程。由于您不知道哪个会先返回,因此将它们都关闭并在两者都传送了数据后执行某些操作。
这假设您有某种回调,可以自定义在 api 完成请求时调用。
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.
我认为旗帜可能是最好的。或者,如果您想强制执行一系列请求,您可以执行同步 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.
我想你已经差不多了。也许使用具有三种状态的小型状态机,noResponse、oneResponse 和 BothResponses(隐含),大致如下:
我假设您需要的所有数据都在您的两个调用对象中,您可以检查它们并进行交叉检查在 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:
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().
如果您使用 AJAX 调用,我会将依赖于第一组数据的(第二个)调用放入第一个调用的回调处理程序中:
使用 jQuery:
这是另一个并行执行此操作的解决方案:
注意我还没有测试过这个。
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:
Here's another solution that does it in parallel:
Note I haven't tested this.