function readData(field) {
var profileDatabase = firebase.database();
var user = firebase.auth().currentUser;
var name = user.email.substring(0, user.email.indexOf("@"));
return profileDatabase.ref('/users/' + name + 'id').once('value').then(function (snapshot) {
return snapshot.val()[field];
});
}
我希望readData函数返回snapshot.val()[field],但Promise是异步的。我怎么解决这个问题?
答案 0 :(得分:2)
您所做的完全正确:从then
回调中返回,并从then
返回调用readData
的结果。承诺then
创建后会使用该值自行解决,使用readData
的来电者会在then
回调中看到它。
readData(field).then(function(value) {
// Here, `value` is the value from `snapshot.val()[field]`
});
这是一个示例(使用setTimeout
来模拟数据库操作):
function fakeDatabaseOperation() {
return new Promise(function(resolve) {
setTimeout(function() {
resolve({
val: function() {
return {foo: "bar"};
}
});
}, 500);
});
}
function readData(field) {
/*
var profileDatabase = firebase.database();
var user = firebase.auth().currentUser;
var name = user.email.substring(0, user.email.indexOf("@"));
*/
return fakeDatabaseOperation().then(function (snapshot) {
console.log("Got snapshot here");
return snapshot.val()[field];
});
}
readData("foo").then(function(val) {
console.log("Value here: " + val);
});