数组没有找到全局变量?

时间:2017-06-26 14:48:13

标签: javascript node.js scope

我认为此时我理解了范围和承诺/同步性,但是当我在node.js中运行它时,我有一个棘手的时间弄清楚为什么这块代码会继续返回'undefined'

var playerName; 
var teamName;
var tweets = [];

function composeTweet(){

    tweets = [ playerName + ' plays basketball for the ' + teamName,
               teamName + ' want to trade for ' + playerName,
               'what if ' + playerName + ' got traded to the ' + teamName];


    function getPlayer() {
        // some code, new promise, etc ... this stuff works locally ...
        playerName = 'Tim';
    }

    function getTeam(){
        // code, promise ... works here also ...
        teamName = 'Spurs';
    }

    getPlayerName().then(function(){
        return getTeamName();
    }).then(function(){
        // sendTweet();
        console.log(tweets[1]);

    }).catch(function(fromReject) {
        console.log('error?');
    });
}

composeTweet();

这应该打印:

  

马刺希望交易蒂姆

但我得到了:

  

未定义想要交易未定义的

在这种情况下,playerName和teamName不是全局变量吗?我误解了如何使用承诺吗?如何在不使用window.playerName的情况下引用全局变量(我不认为这在node.js中有效,对吗?)?

我对编程很不熟悉,如果这是重复的话,请道歉!非常感谢!!!

1 个答案:

答案 0 :(得分:0)

当您设置tweets变量时,playerNameteamName值未定义,因为在您分配任何值之前已完成它们。

您必须在tweetsplayerName之后设置teamName变量。

关于变量范围和承诺,代码没问题。