gpt4 book ai didi

javascript - 在 JavaScript 中异步执行代码

转载 作者:行者123 更新时间:2023-11-28 15:11:23 25 4
gpt4 key购买 nike

我目前正在学习如何使用 Angular.js,并尝试使用类似 REST 的 API 编写自己的身份验证代码。下面是我的身份验证服务的代码。

我的 signIn 的问题功能是它总是返回 false,即使我的 api 返回 HTTP 200 。一段时间后,我发现正是由于 javascript 的同步特性,return response;语句在response = res.data.key;之前执行声明。

我不知道赋值完成后如何执行 return 语句(如果响应是 HTTP 200 )。我该怎么做?

angular.module('app').factory('auth', ['Base64', '$http', function(Base64, $http) {
return {
signIn: function(email, password) {
var response = false;
var encoded = Base64.encode(email + ':' + password);
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
$http.post('api/v1/sign_in', {}).then(function(res) {
if (res.status == 200) {
response = res.data.key;
}
});
return response;
}
}
}]);

最佳答案

使用$q.defer() :

angular.module('app').factory('auth', ['Base64', '$http', '$q', function(Base64, $http, '$q') {
return {
signIn: function(email, password) {
var response = false;
// You create a deferred object
// that will return a promise
// when you get the response, you either :
// - resolve the promise with result
// - reject the promise with an error
var def = $q.defer();
var encoded = Base64.encode(email + ':' + password);
$http.defaults.headers.common.Authorization = 'Basic ' + encoded;
$http.post('api/v1/sign_in', {}).then(function(res) {
if (res.status == 200) {
response = res.data.key;
// success: we resolve the promise
def.resolve(response);
} else {
// failure: we reject the promise
def.reject(res.status);
}
});
// You return the promise object that will wait
// until the promise is resolved
return def.promise;
}
}
}]);

现在,您可以执行以下操作:

auth.signIn().then(function(key) {
// signin successful
// do something with key
}).catch(function(err) {
// signin failed :(
// do something with err
}).finally(function() {
// you could do something in case of failure and success
})

关于javascript - 在 JavaScript 中异步执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36309956/

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