[英]How to pass promise result into outer function?
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];
});
}
I want the readData function to return snapshot.val()[field], but Promise is asynchronous. 我希望readData函数返回snapshot.val()[field],但Promise是异步的。 How can I resolve that?
我怎么解决这个问题?
What you've done is exactly right: Return it from the then
callback, and return the result of calling then
from readData
. 你所做的完全正确:从
then
回调中返回它, then
从readData
返回调用的结果。 The promise then
creates will resolve itself with that value, and the caller using readData
will see it in their then
callback. then
创建的promise将使用该值解析自身,并且使用readData
的调用者将在其then
回调中看到它。
readData(field).then(function(value) {
// Here, `value` is the value from `snapshot.val()[field]`
});
Here's an example (using setTimeout
to simulate the database operation): 这是一个例子(使用
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); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.