目前我正在阅读这两个答案,以更好地理解问题并更好地使用 javascript:
wait for async task to finish Promises in AngularJS and where to use them?
但目前我有这段代码:
function getRegistration(id) {
var numRegistered = 0;
api.search({num: id, state: "done"})
.then(function(response) {
numRegistered = response.data.content.length;
)};
console.log(numRegistered);
}
现在我可以预期 numRegistered 为 0,因为它可能在异步调用完成之前执行该语句。我发现很难理解如何执行此操作,以便我等待调用、分配值并返回它......解决方案似乎是使用回调函数或使用 promise 。有人可以帮助我吗(是的,我来自面向对象的背景......)。
api.search 基本上执行 $http.get。
最佳答案
这是 promise 方法:
function getRegistration(id) {
return api.search({num: id, state: "done"}); // we just return the promise
}
然后,在您的 Controller 或服务中,您将等待它解析:
getRegistration(id).then(function(res) {
var numRegistered = res;
// rest of the code here
});
但是,虽然现在你的函数返回了一些东西(一个 promise ),但你仍然需要等待 promise 得到解决,然后才能使用 numRegistered
。
这与原始 .then
回调中发生的情况非常相似,但这里我们将非 getRegistration 代码移至 getRegistration
函数之外,假设getRegistration
位于某个服务内部,该服务不应该了解其余代码。
关于JavaScript 异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25889271/