简体   繁体   English

JavaScript异步问题

[英]JavaScript Asynchronous Issue

I am trying to use the twitter API to get search results and then modify them, before displaying them on the page. 我正在尝试使用twitter API获取搜索结果,然后对其进行修改,然后再在页面上显示它们。

I am new to the idea of Asynchronous functions and I dont see how to run this method for several search strings and work on the results: 我对异步函数的概念是陌生的,我看不到如何对多个搜索字符串运行此方法以及如何处理结果:

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);

I need to run search/tweets several times and build up an array of the results so they can be analysed. 我需要多次运行搜索/推文,并建立一系列结果,以便对其进行分析。 I dont know how to do this if I have to work in the function? 如果我必须在函数中工作,我不知道该怎么做? Putting it into a callback function would have the same problem. 将其放入回调函数中将具有相同的问题。

The basic idea is this: keep track of how many search terms you are querying, and process the analysis when the last one finishes. 基本思想是:跟踪要查询的搜索词数,并在最后一个词完成时进行分析。

var results = [];
var count = 0;

for (s in searches) {

    client.get('search/tweets', {q: searches[string]}, function(error, tweets, response){
       console.log(tweets); 
       results += tweets;
       if (++count == searches.count) analyse(results);
    });

}

There are also more "modern" ways of handling async code including promises , which I encourage you to check out in your async endeavours. 还有更多“现代”方式来处理异步代码,包括promise ,我鼓励您检查一下异步工作。

For things like this I like to use Promises. 对于这样的事情,我喜欢使用Promises。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/zh-CN/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); 
});

There are basically two working parts here. 这里基本上有两个工作部分。 (1) Running a function on an interval and (2) making an async call. (1)按间隔运行一个函数,以及(2)进行异步调用。

Run a function at an interval 间隔运行一个函数

The first is the ability to run a function at an interval. 第一个是间隔运行功能的能力。 This can be accomplished the following way. 这可以通过以下方式完成。

var myInterval = setInterval(function() {
  // do something here every second
}, 1000);

Make an Async Call 拨打异步电话

The second is making an asynchronous call. 第二个是进行异步调用。 An asynchronous call is asynchronous because the result cannot be guaranteed to exist at the time of execution. 异步调用是异步的,因为不能保证结果在执行时就存在。 You must perform any analysis/data manipulation inside of the async call. 您必须在异步调用内部执行任何分析/数据操作。 This is the only way to guarantee a response. 这是保证响应的唯一方法。

Assuming, based on your example, that client.get() is the asynchronous call, you would do something like this: 假设根据您的示例, client.get()是异步调用,您将执行以下操作:

client.get('search/tweets', ..., function(err, tweets, response) {
  // perform some actions on the result
  analyse(tweets);
});

Putting it all together: 放在一起:

// make a request every second
var myInterval = setInterval(function() {

  // perform async operation
  client.get('search/tweets', ..., function(err, tweets, response) {   

    // perform operations on result
    analyse(tweets);
  });

}, 1000);

function analyse(tweets) {
  // do something with data here
});

It sounds like you're wanting these requests to work in serial(executing one request at a time)... In pure JS, it would go something like: 听起来您想让这些请求以串行方式运行(一次执行一个请求)...在纯JS中,它将类似于:

var results=[], i=0, l=searches.length;

var next=function(callback){

    if(i<l)
    {
        client.get("search/tweets", {q:searches[i]}, function(err, tweets, response){

            results.push(tweets);

            next(callback);
        });
    }
    else
    {
        callback(results);   
    }
};

next(function(results){
    analyze(results);
});

However, these days, as noted by realseanp, Promises make this way cleaner(although his answer would run the requests in parallel). 但是,正如realseanp所指出的那样,如今,Promise使这种方式变得更加干净(尽管他的回答将并行运行请求)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM