gpt4 book ai didi

javascript - AngularJS $q.resolve()、ES6 Promise.resolve()(和其他动物)

转载 作者:行者123 更新时间:2023-11-29 14:44:17 26 4
gpt4 key购买 nike

免责声明:这里实际上提出了两个问题,但我觉得它们密切相关。

我正在尝试将 promise 对象传递给指令,并且我想在 promise 解析后立即在指令中运行一些初始化代码。

在我的 Controller 中:

$scope.item = $http.get(...)
.success(function (result) {
$scope.item = result.item;
});

$scope.item 被传递给指令(通过名为 item 的独立作用域中的属性)。指令链接函数最终会执行如下操作:

Promise.resolve(scope.item)
.then(function () {
initialize();
});

这在 Firefox 中运行良好,但是当我在 IE 上运行它时,我得到一个错误,因为未定义 Promise。这个问题让我意识到我可能需要使用 AngularJS $q 服务来提供浏览器之间的一致性,当我查看文档时我发现了另一个问题,起初看起来很小但实际上让我头疼: success() 函数已弃用,我应该改用 then(successCallback)。简单易行,我想,但是一旦我更改 Controller 中的 success 调用,代码也会在 Firefox 中停止工作!我不知道为什么。所以这是第一个问题。

第二个问题是(即使我将成功调用留在 Controller 中)如果我修改指令链接函数中的代码以将 $q 与我认为等效的代码一起使用:

$q.resolve(scope.item, function() { initialize(); });

这仍然根本不起作用。有什么建议吗?

最佳答案

你需要使用 Angular 的 $q 不仅因为它可以跨浏览器工作——还因为它是 deeply linked to Angular's digest cycles .其他 promise 库 can accomplish this feat但是本地 promise 不能轻易做到这一点。

$q.when 所做的(Promise.resolve 的 $q 版本)是将值或 promise 转换为 $q promise 。您不需要这样做,因为您已经在使用 Angular 自己的 $http API,它已经返回了 promise 。

我强烈建议您将网络调用放在服务中并且不要直接影响范围 - 然后调用这些服务来更新范围。

模式基本上是:

$http.get(...) // no assign
.success(function (result) { // old API, deprecated
$scope.item = result.item; // this is fine
});

或者使用更好的 then promise API has the benefits of promises over callbacks比如链接和错误处理:

$http.get(...).then(function (result) {
$scope.item = result.data;
});

关于javascript - AngularJS $q.resolve()、ES6 Promise.resolve()(和其他动物),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34515862/

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