Feel Physics
Feel Physics

Reputation: 2783

want to get not Deferred object but array

I want to get tweets by code twitter.tweets(), but ajax method of class Twitter returns only Deferred object such as shown bottom of this question.

class Twitter
  tweets = []

  getTweets: ->
    tweets_array = []
    $.getJSON('http://search.twitter.com/search.json?callback=?&rpp=100&q=%40weed_7777')
    .done((data) =>
      $.each data.results, (i, item) ->
        tweets_array.push item.text
      @tweets = tweets_array
    )

twitter = new Twitter

###
Present Code
###
twitter.getTweets()
.done ->
  console.log twitter.tweets

###
Ideal Code ... very simple !
###
console.log twitter.tweets()

Thanks for your kindness.

Upvotes: 0

Views: 50

Answers (1)

robkuz
robkuz

Reputation: 9934

If you work with Javascript you should be highly aware of the fact that you are working in an asynchronous/evented environment. So in the end you will be forced to get used to this. Of course there are some strategies to make life easier for example by using the async library (https://github.com/caolan/async)

async.series [
    (callback) => 
        $.getJSON('http://search.twitter.com/search').done (data) => 
            @tweets = (item for item in data)
            callback(null, pass_some_data_if_you_want)
    ,
    (callback) =>
        $.getJSON('http://search.twitter.com/some_other_search').done (data) => 
            do_what_ever_you_want_and_need()
            callback(null, pass_some_data_if_you_want)
    ],
    (error, result) => handle_error_case(error)

Obviously this makes only sense if you multiple actions that you want to execute in series. If you just have one. than your code

twitter.getTweets().done -> console.log twitter.tweets

is the best way to go.

Upvotes: 2

Related Questions