gpt4 book ai didi

javascript - 困惑 : $q. when() 还是只调用一个没有它的函数?

转载 作者:行者123 更新时间:2023-11-28 17:43:27 28 4
gpt4 key购买 nike

总的来说,我对 AngularJS 和 JavaScript 比较陌生。我最近一直在尝试通过创建自己的项目来学习。我注意到我的应用程序的功能在如下代码之间没有明显差异:

$q.when(authenticationService.login($scope.username, $scope.password))
.then(function (response) {

}, function (error) {

});

还有这个:

authenticationService.login($scope.username, $scope.password)
.then(function (response) {

}, function (error) {

});

看来 $q.when 并不是那么必要。我已经阅读了一些内容,我认为缺乏差异可能是由于我的 authenticationService.login() 返回了一个 promise 。但仅仅是为了这个吗? $q.when() 只是为了确保里面的内容是一个 promise 吗? (所以如果是,它会留下它,如果不是,它会将它包装在一个 promise 中)?还有哪些可能的其他用例?谢谢!

最佳答案

The documentation似乎很清楚这一点:

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

如果术语“thenable”(他们写成“then-able”)不熟悉,那么值得回顾一下 Promises/A+ spec .

关于javascript - 困惑 : $q. when() 还是只调用一个没有它的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47380089/

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