我正在尝试使用 twitter API 获取搜索结果,然后修改它们,然后再将它们显示在页面上。
我对异步函数的想法很陌生,我不知道如何针对多个搜索字符串运行此方法并处理结果:
var results = [];
for (string in searches) {
client.get('search/tweets', {q: searches[string]}, function(error, tweets, response){
console.log(tweets); // I need to put these in an array (results) and get the next lot
});
}
analyse(results);
我需要多次运行搜索/推文并构建结果数组,以便对其进行分析。如果我必须在该功能中工作,我不知道该怎么做?将其放入回调函数中也会出现同样的问题。
最佳答案
对于这样的事情,我喜欢使用 Promise。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
let promises = [];
// for each string you have create a new promise and put it in an array
for (string in searches) {
promises.push(new Promise((resolve, reject) => {
client.get('search/tweets', {q: searches[string]}, function(error, tweets, response){
resolve(tweets);
});
}));
}
// after your loop use Promise.all to wait until all promises are resolved and then do something with the results
Promise.all(promises).then(results => {
console.log(results);
});
关于JavaScript 异步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287215/