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

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

问题描述

我有三个API网址,每个网址都有相同的对象名称,我希望同时调用所有api.

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

到目前为止,我的js:

My js so far:

$(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.

如果您想对所有三个服务执行任何操作,我建议您使用

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网址并同时调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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