據我所知,你是不希望保存數據,而只是收集多個異步調用的結果ce全部完成後將數據交付給客戶?如果是這樣,您可以使用async或promises。
在堆棧溢出中已經有這樣的例子,例如。這Node.js: Best way to perform multiple async operations, then do something else?但這裏反正兩個簡化的實現。
使用異步
var async = require('async');
// ...
var tweets = function(y) {
return function(cb) {
client.get('statuses/user_timeline', {screen_name: y, count: 1},
function(err, data) {
// Process the data ...
cb(null, processedTweets);
}
);
}
};
var mentions = function(x) {
return function(cb) {
client.get('search/tweets', {q: x , count: 1},
function(err, data) {
// Process the data ...
cb(null, processedMentions);
}
);
}
};
app.get('/mytweetsapi', function(req, res) {
var tasks = [];
if (string.checktweet1 == 'on') {
tasks.push(tweets(string.teamname));
}
if (string.checkmentions1 == 'on'){
tasks.push(mentions(string.teamname));
}
if (string.checktweet2 == 'on'){
tasks.put(tweets(string.playername));
}
if (string.checkmentions2 == 'on'){
tasks.put(mentions(string.playername));
}
async.parallel(tasks, function(err, results) {
// Process the results array ...
res.json(processedResults);
});
});
使用承諾
var Promise = require('bluebird');
// ...
var tweets = function(y) {
return new Promise(function(resolve, reject) {
client.get('statuses/user_timeline', {screen_name: y, count: 1},
function(err, data) {
// Process the data ...
resolve(processedTweets);
}
);
});
};
var mentions = function(x) {
return new Promise(function(resolve, reject) {
client.get('search/tweets', {q: x , count: 1},
function(err, data) {
// Process the data ...
resolve(processedMentions);
}
);
});
};
app.get('/mytweetsapi', function(req, res) {
var tasks = [];
// Same if this then tasks.push as in async example here
Promse.all(tasks).then(function(results) {
// Process the results array ...
res.json(processedResults);
});
});
我不知道你用的是什麼HTTP客戶端,但你也許可以用var client = Promise.promisifyAll(require('your-client-lib'));
轉換的方法,以返回承諾,然後您可以將tweets
和mentions
函數轉換爲
var tweets = function(y) {
return client.get('statuses/user_timeline', {screen_name: y, count: 1});
};
這種方式雖然在Promise.all
的results
有不同的反應,你需要確定哪些是tweets
的,哪些是mentions
正確處理它們。
這是你的服務器端代碼?你在使用任何數據庫嗎?你可以讀/寫/從一個'JSON'文件進行開發 – cl3m
@ cl3m這是服務器端代碼。我沒有使用數據庫。我只是想將我從twitter api收到的數據直接發送到我的Web界面 –
如何從您的Web界面調用您的服務器代碼?你在使用某種Ajax調用嗎? – cl3m