【发布时间】:2021-11-09 18:44:50
【问题描述】:
我正在通过 Chrome 控制台操作一些角度服务/功能。 (我必须专门为我正在处理的任务执行此操作)。
我要做的是等待AddBagIfLimitNotReached() 函数执行并完成运行。然后才访问变量this.option.Quantity。
angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = async function(n) {
console.log("tthis", this)
if (this.HasReachedMaximumBaggageAllowance()) {
angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
return;
}
this.AddBag(n);
console.log("Quantity", this.option.Quantity);
};
使用此功能,我将产品添加到我的购物篮中。 this.option.Quantity 应该是 console.log 1。但它实际上是consoles.log 0。
但是,如果我检查对象本身,它会显示 1。
所以我认为发生了什么,是我在控制台记录我的包数量,在包实际上完成添加到购物篮之前。
例如,如果我添加了一个 2 秒的 settimeout,则正确的包值 = 1 是 console.logged。
angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = async function(n) {
console.log("tthis", this)
if (this.HasReachedMaximumBaggageAllowance()) {
angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
return;
}
this.AddBag(n);
// Returns 1
setTimeout(function(){ console.log("Quantity", this.option.Quantity); }, 2000);
};
有没有更好的方法可以在不使用 settimeout 的情况下实现这一目标?我已经尝试过 async/await/promises,但我似乎仍然找不到等待函数完成加载的方法。
Async/await 返回错误 - 它不喜欢函数 this.HasReachedMaximumBaggageAllowance() 并抛出错误声明 this.HasReachedMaximumBaggageAllowance is not a function。
任何提示/想法将不胜感激。
【问题讨论】:
-
我认为您需要向我们展示
HasReachedMaximumBaggageAllowance和AddBag函数。否则,很难判断你是否做对了。 -
另外,
this绑定到什么?Scope? -
是的,它绑定到 Scope,它基本上是一个对象,其中包含有关正在添加的包的数据。例如。 this.option.quantity = 1. this.bag.weight = 50kg。等等等等 - HasReachedMaximumBaggageAllowance() 检查行李限制。 addBag 将包对象发布到服务器。问题是,代码太多了,无法分享。就这两个功能而言,它实际上是数百行。
标签: angularjs asynchronous async-await promise