-3
我想我理解的范围和承诺/同步在这一点上,但我有一个棘手的时间弄清楚为什么这个块的代码不断回报“未定义”当我在node.js中运行它全局变量不被数组找到?
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,对吗?)?
我大多是新编程,所以如果这是重复的道歉!非常感谢!!!
该代码没有真正意义..你从来没有分配任何东西给'playerName'或'teamName'(设置它们的函数永远不会被调用),所以当然它们是未定义的。 –
'tweets'中的字符串是在调用'composeTweet'函数时创建的。如果稍后更改变量值,它不会自动更新已创建的字符串。如果你想获得变量的当前值,你必须使它们成为函数。 – JJJ
换句话说,如果你做'var a =“Hello”; var b = a +“World!”; a =“再见残忍”;'b'的值仍然是''Hello World!“' - 承诺与它没有任何关系。 – JJJ