gpt4 book ai didi

javascript - 如何在 angularjs 中编写返回 promise 的异步方法?

转载 作者:行者123 更新时间:2023-11-30 17:20:57 25 4
gpt4 key购买 nike

我正在开发 AngularJS 应用程序。

我尝试编写一个服务方法,它可以定期从 HTTP 请求中自动重新加载一些内容并通知调用该方法的 Controller 。

所以我搜索使用 AngularJS 的 promse API 并使用 $timeout 服务,但是当方法非异步运行时我无法返回 promise ...

所以在这里,promise 永远不会返回,我明白为什么,但我不知道做我想做的事情的正确模式是什么。

angular.module('myModule')

.factory('myService', [
'$timeout',
'$q',
'$doMyHttpRequest',
function($timeout, $q, $doMyHttpRequest){

var d = $q.defer();

return function(){
autoRefresh = function(){

$timeout(function(){
$doMyHttpRequest(function(){
d.notify({ // notify the update success
updated: true
});
},function(){
d.notify({ // notify the update error
updated: false
});
});
this.autoRefresh(); // refresh again in 60 seconds
},60000);

};
this.autoRefresh();

return d.promise;
}

}])

.controller('myCtrl', ['myService', function(myService){

myService().autoRefresh().then(function(){ // never reached because promise is never returned
// do my stuff when succeed
},function(){ // never reached because promise is never returned
// do my stuff when error
});

}])

;

最佳答案

请看这里:http://jsbin.com/wiveli/1/edit

app.controller('firstCtrl', function($timeout,  doMyHttpRequest){

function onSucess() {

console.log("sucess");
autoRefresh();

};
function onError() {

console.log("error");
autoRefresh();

}


function autoRefresh(){




$timeout(function(){
doMyHttpRequest.getData().then(onSucess, onError);

},1000);

}
autoRefresh();

});

关于javascript - 如何在 angularjs 中编写返回 promise 的异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25139302/

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