更新回调内的数组

时间:2013-08-27 02:37:53

标签: javascript asynchronous callback

我有以下两个功能:

var abc;

function updateNum() {
    abc=0;
    g.dbm.transaction("leagues").objectStore("leagues").openCursor(null, "prev").onsuccess = function (event) {
        var teams, i;

        team.filter({
            attrs: ["tid", "abbrev", "region", "name", "cid"],
            seasonAttrs: ["winp", "playoffRoundsWon"],
            season: g.season
        }, function (teams) {
            // Sort teams by playoffs and winp, for first round
            teams.sort(function (a, b) {
                if (a.playoffRoundsWon < b.playoffRoundsWon) {
                    return -1;
                }
                if (a.playoffRoundsWon > b.playoffRoundsWon) {
                    return 1;
                }
                return a.winp - b.winp;
            });
            abc+=1;
        });
    };
}

function getNum() {
  return abc;
}

我要做的是更新回调函数中的变量abc然后返回它。我这样做是先调用另一个文件中的updateNum()函数。然后我将一个变量赋值给getNum()

以下是示例代码的外观:

myFile.updateNum();
var number = myFile.getNum();

我目前无法返回num的更新值。 number保持返回0(默认值)而不是新更新的值(即1)。

如何让它显示更新的值?如果我需要添加更多信息,请告诉我。

2 个答案:

答案 0 :(得分:1)

好吧,如果updateNum是异步的,则必须将回调作为参数,以便在更新号码时通知您。

E.g。

var num = 0;

function updateNumAsync(callback) {
    setTimeout(function () { 
        num = 1;
        callback && callback(num); //call the callback if provided 
    }, 500);
}

updateNumAsync(function (num) {
    console.log(num); //updated num
});

答案 1 :(得分:1)

这是使用带回调的异步函数来传递异步结果的一般模式。什么是team.filter?您需要设计代码,以便异步部分调用传递给封闭函数的callback()函数。

如果过滤会给您带来问题,您可能需要查看https://github.com/caolan/async#filterarr-iterator-callback

(function main(){
  getNum(function(err, abc){ 
    console.log('thx for playing '+abc)
  });
})();

function getNum(anotherCallback) {
  // Whatever code relies on the result of an asynchronous function must be
  // placed inside the callback function
  countTeams(function(abc){
    console.log('countTeams completed, abc='+abc);
    var err = null;
    anotherCallback(err, abc);
  });
};

function countTeams(callback){
  var abc=0;
  g.dbm.transaction("leagues").objectStore("leagues").openCursor(null, "prev").onsuccess = function (event) {
    var teams, i;
    // I don't know what this filter function does, I am assuming it's synchronous
    team.filter({
      attrs: ["tid", "abbrev", "region", "name", "cid"],
      seasonAttrs: ["winp", "playoffRoundsWon"],
      season: g.season
    }, function (teams) {
      // Sort teams by playoffs and winp, for first round
      teams.sort(function (a, b) {
        if (a.playoffRoundsWon < b.playoffRoundsWon) {
          return -1;
        }
        if (a.playoffRoundsWon > b.playoffRoundsWon) {
          return 1;
        }
        return a.winp - b.winp;
      });
      abc+=1;
    });
    return callback(abc); // 0 or n depending on what team.filter does
  };
};