javascript - 为什么promise会这样解决呢? (使用通知回调)

标签 javascript angularjs angular-promise

我正在使用 Angular 检查 Stomp Chat 客户端的代码,开发人员创建了一个名为 receive 的服务,该服务返回一个 promise 。然后在 Controller 中,它解决了 promise ,但是......我不理解结构。

ChatService.receive().then(null, null, function(message) {
  $scope.messages.push(message);
});

据我了解,then有两个参数,onSuccess函数和onError函数。那为什么前两个是空的,而第三个是处理成功的呢?如果我需要处理错误,我该怎么做?

最佳答案

第三个参数是 notifyCallBack 函数。

来自文档:

The Promise API

Methods

  • then(successCallback, [errorCallback], [notifyCallback]) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.

    This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining). It also notifies via the return value of the notifyCallback method. The promise cannot be resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback arguments are optional.

— AngularJS $q Service API Reference (The Promise API)

注意:

Promise 通知撰写得不好 1并且不属于ES6 Promises的一部分。相反,请考虑使用 rxJS Observables广泛用于 Angular 2+并为 future 提供更好的道路。

关于javascript - 为什么promise会这样解决呢? (使用通知回调),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44186320/

相关文章:

javascript - 在匿名函数中声明函数

javascript - Swiper - OpenCart - 背景全尺寸图像不起作用

javascript - Angular 调用随机服务!为什么?

javascript - 绑定(bind)输入并选择一个 ng-model

javascript - 当某些调用有效而其他调用失败时 $q.all() 会发生什么?

AngularJS : How to test promise logic with a resolve in it?

javascript - 在html5中一个接一个地播放视频

javascript - WebRTC - 如何设置始终使用 TURN 服务器?

javascript - Angular 路由中的哈希符号

angular - Angular2 中的 Promise 和箭头函数