【发布时间】:2017-11-29 10:54:27
【问题描述】:
我以为我现在理解范围和承诺/同步性,但我很难弄清楚为什么当我在 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();
这应该打印出来:
马刺想要交易蒂姆
但是我得到了:
undefined 想用 undefined 交易
在这种情况下 playerName 和 teamName 不是全局变量吗?我是否误解了如何使用承诺?如何在不使用 window.playerName 的情况下引用全局变量(我认为这在 node.js 中不起作用,对吗?)?
我大多是编程新手,如果这是重复的,我深表歉意!非常感谢!!!
【问题讨论】:
-
代码没有真正的意义..你永远不会给
playerName或teamName分配任何东西(设置它们的函数永远不会被调用),所以它们当然是未定义的。 -
tweets中的字符串是在调用composeTweet函数时创建的。如果您稍后更改变量值,它不会自动更新已创建的字符串。如果要获取变量的当前值,则必须使它们起作用。 -
换句话说,如果你使用
var a = "Hello"; var b = a + " World!"; a = "Goodbye Cruel";,b的值仍然是"Hello World!"——promise 与它没有任何关系。
标签: javascript node.js scope