我有一个按钮,它执行一个函数, promise 从 firebase 获取和显示 html 中的数据(我使用的是 angularJS、ionic 和 firebase)。
问题是:如果我不在其后包含 .then(function(){}) ,promise 将以异步方式执行,这意味着我必须再次单击该按钮,以便数据以 html 格式显示.
我想将数据放在 promise 之后的范围内(从 firebase 获取数据),但出于某种原因,只有在我将 .then 函数放在它之后才有效。
但是,数据在控制台中正常显示,但不是在 html 中(这意味着我认为该函数没有附加到范围)。
这是一段代码:
$scope.displayChat = function () {
var userId = firebase.auth().currentUser.uid; // Get ID
var deferred = $q.defer()
var db = firebase.database();
var ref = db.ref("12346787");
ref.on("value", function(snapshot) {
console.log(snapshot.val());
$scope.chatArray = snapshot.val();
deferred.resolve()
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
})
return deferred.promise.then(function(){
// Removing this empty .then(function(){}) function
// will result in asynchronousity.
// just "return deferred.promise;" doesn't work.
})
}
有什么解决办法吗?我对 promise 没有太多经验,但我没有找到任何相关内容。干杯。
最佳答案
promise的目的是为了管理异步方法,所以我不是很理解问题...
而且正常情况下displayChat里面的代码是必须要执行的,只有callback之后才必须执行。您应该返回 promise ,一旦您确定所需的异步方法已完成,您就可以执行回调。
关于javascript - promise 只能与 then 函数一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41894692/