簡體   English   中英

Node.Js中的回調的問題

[英]Issues with CallBacks in Node.Js

我是Node.js的新手,昨天才開始學習它,我在回調方面苦苦掙扎。 我只想從getId函數返回值並在favorite函數中使用它

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!")
        }
    })
};

不確定T是什么,但這是我猜您正在嘗試做的

    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!")
}
  });});

由於單線程事件循環的本質,幾乎所有用Node.js編寫的程序都是異步的。 在JavaScript中,處理異步函數的傳統方式是回調。 回調是要在異步操作結束時執行的函數。 這種類型的異步操作不會立即返回值(其他語言中的返回類型為void )。 所需的數據將作為參數傳遞給回調函數。 以下代碼顯示了使用回調的正確方法,以及如果您“正常”調用它會發生什么。

JavaScript中的回調可以是預先存在的命名函數,也可以是匿名函數,如以下示例所示。 在Node.js和大多數標准庫中,這些回調具有特定形式的function (err, result) 由於異步函數不能以相同的方式引發錯誤,因此第一個參數用於指示出了問題。 如果您忘記檢查錯誤參數,許多代碼分析器都會警告您。

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

var id = getId(); // undefined

尚不清楚您要使用getId函數做什么。 您在favorite函數中使用它,就像它應該只返回一個ID,但同時也在for循環內執行回調函數,這意味着它將對多個ID執行多次。 其次,您將返回的ID作為第一個參數傳遞給回調。 這實際上意味着確實有問題,並且ID描述了錯誤。 最后,您嘗試同步調用getId favorite函數應首先執行getId ,然后在回調中使用結果。

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

如您所見,回調的數量可以並且將很快嵌套在自身中。 您可以考慮將函數分成多個異步步驟以提高代碼清晰度。 如果您打算獲取ID列表並喜歡每個ID,則可能應該反轉控件結構。 也就是說,在T.get請求的回調中調用favorite

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM