简体   繁体   English

拨打多个api网址并同时拨打电话

[英]call multiple api urls and call at same time

I have three API urls, each have the same object names, I wish to call all apis at the same time. 我有三个API网址,每个网址都有相同的对象名称,我希望同时调用所有api。

My js so far: 我的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 calls are asynchronous, and they execute in the sequence you write them inside your code. API调用是异步的,它们按照您在代码中编写的顺序执行。 execution doesn't really matter because the 'then' could be called in different order as it was executed. 执行并不重要,因为'then'可以在执行时以不同的顺序调用。

If you want to do anything on the execution of all three services i would recommend using async.js . 如果你想对所有三种服务的执行做任何事情,我建议使用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
        }
    })
    // ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM