同步多个API调用 [英] Synchronized multiple API calls

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

问题描述

我需要从两个不同的API端点获取数据,并且在获取了两个数据之后,我应该对这些数据做一些事情(例如,比较来自两个来源的数据).

I need to fetch the data from two different API endpoints, and after both data is fetched I should do something with those data (ie. compare the data from two sources).

我知道如何从一个API提取数据,然后调用回调函数对数据进行处理.我正在这样做,如下.

I know how to fetch the data from one API, and then call the callback function to do something with the data. I am doing this as follows.

function getJSON(options, cb) {
   http.request(options, function(res){
       var body = "";

       res.on("data", function(chunk){
          body += chunk;
      });

       res.on("end", function(){
          var result = JSON.parse(body);
          cb(null, result);
      });

       res.on("error", cb);
   })
   .on("error", cb)
   .end();
}

var options = {
    host: "api.mydata1.org",
    port: 8080,
    path: "/data/users/3",
    method: "GET"
}

getJSON(options, function(err, result) {
    if (err) {
        return console.log("Error getting response: ", err);
    }

    // do something with the data

});

现在,我想要的是这样的东西:

Now, what I would want to have something like:

var options2 = {
        host: "api.mydata2.org",
        port: 8080,
        path: "/otherdata/users/3",
        method: "GET"
    }

这些将是连接到另一个API的选项,并且具有单个回调函数,只要从两个两个API加载的数据都会调用该回调函数.我该怎么办?

Those would be the options to connect to the other API, and have a single callback function that would get called whenever the data from both APIs is loaded. How can I do that?

推荐答案

我建议使用request-promise模块,该模块返回表示异步操作的Promise,然后可以使用Promise.all()来跟踪它们何时都处于完成,然后访问其结果:

I'd suggest using the request-promise module which returns promises that represent the async operations and you can then use Promise.all() to track when both of them are done and then access their results:

const rp = require('request-promise');

function getJSON(options) {
    return rp(options).then(body => {
        return JSON.parse(body);
    });
}

let options1 = {
    host: "api.mydata1.org",
    port: 8080,
    path: "/data/users/3",
    method: "GET"
};

let options2 = {
        host: "api.mydata2.org",
        port: 8080,
        path: "/otherdata/users/3",
        method: "GET"
};

Promise.all([getJSON(options1), getJSON(options2)]).then(results => {
    // process results here
    console.log(results[0]);      // from options1 request
    console.log(results[1]);      // from options2 request
}).catch(err => {
    // process error here
    console.log(err);
});

您可以阅读有关Promise.all()的信息在MDN 上. Web上有很多关于诺言的文章和教程.这是一个.它们是ES6 Javascript中的标准配置,并且已通过库在ES5中使用了多年.它们是Java语言中用于管理或协调异步操作的选定方案.如果您正在用Javascript进行任何异步编程(几乎所有node.js编程都这样做),那么您应该学习Promise.

You can read about Promise.all() on MDN. There are lots and lots of articles and tutorials about promises in general on the web. Here's one. They are standard in ES6 Javascript and have been available for years in ES5 through libraries. They are the chosen scheme in the Javascript language for managing or coordinating asynchronous operations. If you're doing any async programming in Javascript (which pretty much all node.js programming does), then you should learn promises.

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

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