同步访问两个远程资源并在组合响应中输出 - NodeJS

Access two remote resources synchronously and output it in combined response - NodeJS

简而言之

我需要访问两个或多个远程资源提要,将其合并并显示为来自我的 nodejs 服务的一个结果。


详细

我需要从多个提供者获取提要(根据仪表板对象中存储的内容,数量可能会有所不同)

连接它们,进行一些其他数据操作,最后将内容显示为一个数组。

var allFeeds = [];
dashboard.providers.forEach(function(provider) {
  if (provider.source === 'facebook') {
    ...
    fb.getFeeds(provider.data.id, function(feeds) {
      ...
      Array.prototype.push.apply(allFeeds, feeds);
    });
  } else if (provider.source === 'google') {
    ...
    google.getFeeds(provider.data.id, function(feeds) {
      ...
      Array.prototype.push.apply(allFeeds, feeds);
    });
  } else if (provider.source === 'twitter') {
    ...
    twitter.getFeeds(provider.data.id, function(feeds) {
      ...
      Array.prototype.push.apply(allFeeds, feeds);
    });
  }
});
...
// other data manipulations
...
res.json(allFeeds);

由于 nodejs 具有异步网络调用,我该如何实现?

你可以通过承诺实现这一目标,我将通过 bluebird.js

向你展示
var Promise = require('bluebird');

var fbFeedAsync = Promise.promisify(fb.getFeeds);
var googleFeedAsync = Promise.promisify(google.getFeeds);
var twitterFeedAsync = Promise.promisify(twitter.getFeeds); 

function getFeedFor(type, id) {
 if (type === 'twitter') {
  return twitterFeedAsync(id);
 } else if (type === 'google') {
  return googleFeedAsync(id);
 } else if (type === 'facebook') {
  return fbFeedAsync(id);
 }
}

var feedRequests = dashboard.providers.map(function(provider) { 
  return getFeedFor(provider.source, provider.data.id);
});

Promise.all(feedRequests).then(function(allFeeds) { // you can use Promise.settle (depending on your use case)
 console.log(allFeeds);
});

您可以使用 async

var async = require('async');
var allFeeds = [];
var tasks = [];

dashboard.providers.forEach(function (provider) {
  if (provider.source === 'facebook') {
    ...
    tasks.push(function (done) {
      fb.getFeeds(provider.data.id, function (feeds) {
        ...
        Array.prototype.push.apply(allFeeds, feeds);
        done();
      });
    });
  } else if (provider.source === 'google') {
    ...
    tasks.push(function (done) {
      google.getFeeds(provider.data.id, function (feeds) {
        ...
        Array.prototype.push.apply(allFeeds, feeds);
        done();
      });
    });
  } else if (provider.source === 'twitter') {
    ...
    tasks.push(function (done) {
      twitter.getFeeds(provider.data.id, function (feeds) {
        ...
        Array.prototype.push.apply(allFeeds, feeds);
        done();
      });
    });
  }
});

async.parallel(tasks, function () {
  ...
  // other data manupulations
  ...
  res.json(allFeeds);
});

您也可以查看这篇 post 我写的是为了构建您的代码以更好地管理异步操作