简体   繁体   中英

Issues with CallBacks in Node.Js

I am new to Node.js, just started learning it yesterday and I am struggling with callbacks. I just want to return the value from the getId function and use it in the favorite function

function getID(callback) {
    var id;

    T.get('statuses/user_timeline', {
        screen_name: config.twitter_account,
        count: 1
    }, function(err, data, response) {
        if (err) {
            console.log("unable to get the id of last tweet")
        } else {
            for (i = 0; i < data.length; i++) {
                //console.log(data)
                console.log("this id of tweet: ", data[i].text, "is: ", data[i].id_str, );
                id = data[i].id_str;
                callback(id);
            }
        }
    });
}

//-------------------------------------------------------------------
// favorite/like a tweet with id
//-------------------------------------------------------------------

function favorite() {
    T.post('favorites/create', {
        id: getID(function(id))
    }, function(err, data, response) {
        if (err) {
            console.log("unable to favorite this tweet, you probably already favored it, TRY SOMETHING ELSE")
            console.log(data);
        } else {
            console.log("The bot WORKED, WE FAVORED YOUR TWEET!")
        }
    })
};

Not sure about what is T but this is what i am guessing you are trying to do

    function getID(callback){

  var id;

T.get('statuses/user_timeline', { screen_name: config.twitter_account , count: 1} , function(err, data, response) {
  if(err){
    console.log("unable to get the id of last tweet")
}
else{
  for(let i=0; i< data.length; i++){
    //console.log(data)
    console.log("this id of tweet: ", data[i].text, "is: ", data[i].id_str, );
    id = data[i].id_str;
    callback(id);
  }
}


 });
}



getID(function (id){T.post('favorites/create', {id: id} , function (err, data, response) {
  if(err){
    console.log("unable to favorite this tweet, you probably already favored it, TRY SOMETHING ELSE")
    console.log(data);
}
else{
  console.log("The bot WORKED, WE FAVORED YOUR TWEET!")
}
  });});

Almost all programs written in Node.js will be asynchronous due to the nature of the single-threaded event loop. In JavaScript, the traditional way of handling asynchronous functions is callbacks. A callback is a function you want executed at the conclusion of an asynchronous operation. This type of asynchronous operation won't return a value immediately (the return type would be void in other languages). The data you want is instead passed to the callback function as a parameter. The following code shows the proper way to use a callback and what happens if you call it “normally”.

A callback in JavaScript can either be a pre-existing, named function, or an anonymous function as in the following example. In the Node.js world and most of the standard libraries, these callbacks have the specific form of function (err, result) . Since asynchronous functions can't throw errors in the same way, the first parameter is used to indicate something went wrong. Many code analyzers will warn you if you forget to check the error parameter.

getId(function (err, id) {
    if (err) {
        // Something went wrong
} else {
        // Everything is fine
        console.log(id);
    }
});

var id = getId(); // undefined

It's a little unclear what you are trying to do with the getId function. You're using it in the favorite function like it should only return a single ID, but you are also executing the callback function inside a for loop, meaning it will execute multiple times for multiple IDs. Secondly, you are passing the returned ID as the first parameter to the callback. This actually means that something did go wrong, and the ID describes the error. Finally, you are attempting to call getId synchronously. Your favorite function should first execute getId and then use the result in the callback.

function favorite() {
    getId(function (err, id) {
        if (err) {
            // Could not get ID
        } else {
            T.post(‘favorites/create’, {id: id}, function (err, data, response) {
                if (err) {
                    // Unable to favorite tweet
                } else {
                    // Successfully favored tweet
                }
            });
        }
    });
}

As you can see, the number of callbacks can and will nest within themselves quite quickly. You may consider splitting a function up into multiple asynchronous steps for code clarity. If your intention was to get a list of IDs and favorite each of them, you should probably invert your control structure. That is, call favorite inside the callback of the T.get request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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