调用多个api url并同时调用 [英] call multiple api urls and call at same time

查看:33
本文介绍了调用多个api url并同时调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个API url,每个都有相同的对象名称,我想同时调用所有的api.

I have three API urls, each have the same object names, I wish to call all apis at the same time.

到目前为止我的js:

$(document).ready(function() {

    var first = 'https:first';
    var second = 'https://second';
    var third = 'https://third';

    $('#get-data').click(function() {
        var showData = $('#show-data');
        $.getJSON(first,second,third function(data) {
            showData.empty();
            var items = data.map(function(elem) {
                return $("<li />", {
                text: elem.title
            });
        });

        var list = $('<ul />').append(items);
            showData.append(list);
        });
    });
});

推荐答案

API 调用是异步的,它们按照您在代码中编写的顺序执行.执行并不重要,因为可以在执行时以不同的顺序调用then".

API calls are asynchronous, and they execute in the sequence you write them inside your code. execution doesn't really matter because the 'then' could be called in different order as it was executed.

如果你想对所有三个服务的执行做任何事情,我建议使用 async.js.看下面的例子:

If you want to do anything on the execution of all three services i would recommend using async.js. look at the following example:

links = ['http://first','http://second','http://third']
data = [];

$('#get-data').click(function() {
    // ...
    async.each(links, function(link,callback){
        $.getJSON(link, function(res){
            data.push(res);
            callback();
        })
    }, function(err){
        if(!err){
            // your code goes here
            // data[0] contains data from link 1
            // data[1] contains data from link 1
            // data[2] contains data from link 2
        }
    })
    // ...
});

这篇关于调用多个api url并同时调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆