gpt4 book ai didi

javascript - Angular 1.x,如何从回调中解决 parent 的 promise

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:28 26 4
gpt4 key购买 nike

我正在尝试包装我的 post/get/put/delete 调用,以便在任何时候调用它们,如果它们失败,它们将检查过期的 token ,如果这是失败的原因,则重试,否则只需解决响应/错误。试图避免重复代码四次,但我不确定如何从非匿名回调中解决。

   factory.post = function (url, data, config) {
var deferred = $q.defer();
$http.post(url, data, config).then(factory.success, factory.fail);

return deferred.promise;
}

factory.success = function (rsp) {
if (rsp) {
//how to resolve parent's promise from from here
}
}

另一种方法是将其复制 4 次:

.then(function (rsp) {
factory.success(rsp, deferred);
}, function (err) {
factory.fail(err, deferred);
});

最佳答案

一个解决方案可能是使用 bind功能。

function sum(a){
return a + this.b;
}

function callFn(cb){
return cb(1);
}

function wrapper(b){
var extra = {b: b};
return callFn(sum.bind(extra));
}

console.log(wrapper(5));
console.log(wrapper(-5));
console.log(wrapper(50));

对于您的解决方案,请检查以下示例

factory.post = function (url, data, config) {
var deferred = $q.defer();
$http.post(url, data, config).then(factory.success.bind({deferred: deferred}), factory.fail.bind({deferred: deferred}));

return deferred.promise;
}

factory.success = function (rsp) {
if (rsp) {
this.deferred.resolve(rsp);
//how to resolve parent's promise from from here
}else {
//retry or reject here
}
}

关于javascript - Angular 1.x,如何从回调中解决 parent 的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216659/

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