$q.defer vs new promise(function (resolve, reject))



我有这个html:

<div class="documentation-comment-view h100" ng-if="views.comment.selected">
<div ng-include="views.comment.templateUrl" class="h100"></div>
</div>
<div class="documentation-annotation-view h100" ng-if="views.annotation.selected">
<div ng-include="views.annotation.templateUrl" class="h100"></div>
</div>
<div class="documentation-localisation-view h100" ng-if="views.localization.selected">
<div ng-include="views.localization.templateUrl" class="h100"></div>
</div>

html 内容根据变量的值而变化。

这是负责它的代码的一部分:

myService.myFunction(param).then(function (retData) {
//Do something here...
changeView(scope.views.comment);
});

我的问题是承诺和这两个函数应该做同样的事情:

功能1:

function myFunction(param) {
var deferred = $q.defer();
//Do something...
deferred.resolve(retData);
return deferred.promise;
}

功能2:

function myFunction(param) {
return new Promise(function (resolve, reject) {
//Do something...
resolve(retData);
});
}

使用这两个函数中的任何一个,我都不会收到任何错误,并且在两个函数中都达到了 changeView。但无论出于何种原因,使用函数 2 都不会更改视图。它仅使用函数 1 工作。

有什么帮助找到发生这种情况的原因吗?谢谢。

承诺

这是一个纯粹的Javascript函数,它不会告诉角度任务的完成情况。 这是一种在不使用 Angular 时处理异步调用的方法。 有关其工作原理的更多详细信息,请参阅此处

$q

一种基于 angular 的服务,可帮助您异步运行函数,并在完成处理时使用其返回值(或异常(,并告诉 angular 再次消化元素并应用更改。 有关更多详细信息,请参阅此处

相关内容

最新更新