Javascript 即使在函数外部初始化变量,也不打印值
我在下面有一个函数,我在函数外部设置了username,但我可以在函数内部得到值,但不能在函数外部得到值。为什么呢?示例如下所示。我试图在外部打印它或调用它,以便它返回该值Javascript 即使在函数外部初始化变量,也不打印值,javascript,Javascript,我在下面有一个函数,我在函数外部设置了username,但我可以在函数内部得到值,但不能在函数外部得到值。为什么呢?示例如下所示。我试图在外部打印它或调用它,以便它返回该值 var username Auth.loggedInUser().then(function (user){ username = user.username console.log(username) <--- this will print the username }); console.log
var username
Auth.loggedInUser().then(function (user){
username = user.username
console.log(username) <--- this will print the username
});
console.log(username) <--- this will print undefined
var用户名
Auth.loggedInUser().then(函数(用户){
username=user.username
console.log(username)这显然是行不通的,因为您使用的是异步运行的。这意味着在Javascript使用console.log(username)
运行第二行时,承诺还没有解决,它会打印未定义的
如果你想使用用户名的值
,你必须等待承诺解决,例如调用中的一个方法,然后
-这个方法将用户名作为一个片段并对其进行处理。这仅仅是因为你使用的是异步的。它没有实现当调用console.log(username)
时(将user.username设置为用户名)。您可以检查
更新:我已更新等待/同步解决方案。
(async () => {
const result = await axios.get('/echo/html/'); // axios.get returns a Promise object
const status = result.status; // you wait until result is fulfilled
console.log(status); // in this way, your get what you want.
})();
console.log(用户名)
在异步调用完成之前,异步调用外部正在运行。不可能。基本上,您点了一个比萨饼,挂断电话后,您就可以吃了。明白了,我不确定实现这一点所需的代码,我正在努力,我明白了这个概念,但可能我不清楚。这就是我目前为止所拥有的;函数getUserName(callback){Auth.loggedInUser().then(function(user){callback(user.name)});}
var username;getUserName(function(result){console.log(result)username=result})console.log(username)
但正如您所见,result将打印值,但username仍将未定义。我如何将此结果值设置为可在这些函数之外使用的变量。@Josh Beam我在尝试使用代码获取值时遇到困难。我明白了这一点,但我不知道如何对其进行编码不确定您的用例是什么,但通常情况下,回调应我会为你做这个把戏。我继续做了这个策略,它成功了,但是我如何将结果保存到回调之外的变量?它仍然显示未定义。这是我到目前为止所做的;function getUserName(callback){Auth.loggedInUser()。然后(function(user){callback(user.name)}
var username;getUserName(函数(结果){console.log(结果)username=result})console.log(用户名)
但正如您所见,result将打印该值,但username仍将是未定义的。如何将该结果值设置为可在这些函数之外使用的变量。@您必须等待承诺对象实现。如果您坚持以同步方式编写,则应使用wait/async,这在我想是你的案子。
var username = 'Rose';
new Promise(resolve => {
resolve('Jack');
})
.then(name => {
username = name;
console.log('A:' + username);
})
.then(() => {
console.log('B:' + username);
})
console.log('C:' + username);
// result:
// C:Rose
// A:Jack
// B:Jack
(async () => {
const result = await axios.get('/echo/html/'); // axios.get returns a Promise object
const status = result.status; // you wait until result is fulfilled
console.log(status); // in this way, your get what you want.
})();