2017-07-31 9 views
0

我有一個函數在下面,我設置了函數外的用戶名,但是我可以在裏面獲得值但不在外面。這是爲什麼?示例如下所示。我想這樣它返回的值即使我初始化函數以外的變量,也不打印值

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 username = Auth.loggedInUser().then(function (user){ 
    return user.username 
}); 
console.log(username) <--- this will Promise {$$state: Object}$$state: Object__proto__: Object 

我怎麼能去外面打印或叫它關於剛調用它時獲取原始用戶名?

+0

異步調用之外的'console.log(用戶名)'在異步調用完成之前正在運行。 –

+0

不可能。基本上你可以點一份披薩,然後你掛斷電話,然後你就可以吃了。 – epascarello

+0

明白了,即時通訊不知道實現這一目標所需的代碼,即時通訊掙扎,我明白了,但也許我不清楚。 –

回答

1

這只是因爲您使用的是異步的Promise。當console.log(username)被調用時,它沒有被滿足(你設置user.username爲用戶名)。你可以檢查example

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 

更新:我更新了的await /同步解決方案,請check

(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. 
})(); 
+0

我在嘗試使用我的代碼獲取值時遇到問題。我明白了,但我不知道如何編寫它 –

+0

不知道你的用例是什麼,但通常回調應該爲你做。 – choasia

+0

我繼續做,並採取了這種策略,它的工作,但我怎麼能將結果保存到回調以外的變量?它仍然會顯示未定義的。 –

0

由於您正在使用異步運行的Promise,因此這種方式無法正常工作。這意味着此時Javascript正在運行第二行console.log(username),承諾尚未解決,它打印undefined

如果您想使用username的值,則必須等到Promise解決爲止,例如調用then-方法,該方法將用戶名作爲參考並正在執行某些操作。