gpt4 book ai didi

javascript - 为什么 $scope.someArray.push 不是传递给 $q.promise 上的 .then 的有效函数

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:23 25 4
gpt4 key购买 nike

相关 fiddle :https://jsfiddle.net/tqf4zea7/1/

我在 Angular Controller 中使用 $q。为了测试某些场景,我在作用域上创建了一个数组以将消息推送到:

$scope.messages = [];

我设置了一个返回 $q 函数的函数:

function returnAPromise(valToReturn){
return $q(function(resolve, reject){
$timeout(function(){
resolve(valToReturn);
}, 500);
});
}

然后我有一个 .then() 调用结果如下:

returnAPromise('third').then($scope.messages.push);

因为我只想将 promise 解决的值推送到数组,我想我可以只传入消息数组的 push 方法,但是当我这样做时,我得到以下错误:

VM289 angular.js:12520 TypeError: Array.prototype.push called on null or undefined
at processQueue (VM289 angular.js:14792)
at VM289 angular.js:14808
at Scope.$eval (VM289 angular.js:16052)
at Scope.$digest (VM289 angular.js:15870)
at Scope.$apply (VM289 angular.js:16160)
at VM289 angular.js:17927
at completeOutstandingRequest (VM289 angular.js:5552)
at VM289 angular.js:5829

如果我将 push 包含在一个函数中,它可以正常工作:

returnAPromise('third').then(function(message){ 
$scope.messages.push(message)
});

这是我不明白的关闭问题吗?

最佳答案

你需要绑定(bind) push 因为它使用 this

returnAPromise('third').then($scope.messages.push.bind($scope.messages));

关于javascript - 为什么 $scope.someArray.push 不是传递给 $q.promise 上的 .then 的有效函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38983026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com