[英]Returning promise after resolving promise in same function
I have library function which needs to return the promise to post something in DB after it resolves another promise.我有库函数,它需要在解决另一个承诺后返回在 DB 中发布某些内容的承诺。 I am trying to chain the promises but not working.我试图链接承诺但不起作用。
postIssue: function (issue) {
return getUserConfiguration()
.success(function (response, status, headers) {
var token = headers("X-XSRF-TOKEN");
if (token) {
_cookie = token;
if (issue.isValid()) {
var url = _baseURL + "/api/issue/";
var data = JSON.stringify(issue);
var config = {
xhrFields: { withCredentials: true },
headers: { "X-XSRF-TOKEN": _cookie }
};
return $http.post(url, data, config);
}
else {
return $q.reject("Issue doesn't have valid fields to submit");
}
}
else {
$q.reject("There is no XSRF token on response header");
}
})
.error(function () {
$q.reject("Error getting user's configuration");
});
}
When I call the function in my code where I use this library It resolves and posts the issue correctly the data in then is shown of the first promise while I need the second one.当我在使用此库的代码中调用该函数时,它会正确解决并发布问题,然后显示第一个承诺的数据,而我需要第二个承诺。
libraryAPI.postIssue(createIssue).then(function (data) {
console.log(data);
},function (error) {
console.log(error);
});
data here is not of the second promise but the first one but Issue is created correctly这里的数据不是第二个承诺,而是第一个,但问题是正确创建的
Several points here.这里有几点。
.then(successCallback, errorCallback)
rather than .success()
and .error()
.使用.then(successCallback, errorCallback)
而不是.success()
和.error()
。.then()
callbacks has one parameter, and so does the error. .then()
回调有一个参数,错误也是如此。response
object in a successful callback also contain the headers and status.成功回调中的response
对象还包含标头和状态。 You can access them like so: response.headers
and response.status
(more information in the Official AngularJS Documentation for $http ).您可以像这样访问它们: response.headers
和response.status
(有关$http的 官方 AngularJS 文档中的更多信息)。 You can either create a $q.defer()
'ed variable and return it at the end (resolve/reject it in the logic), or immediately return a $q.reject
or $q.resolve
.您可以创建一个$q.defer()
ed变量并在最后返回它(在逻辑中解决/拒绝它),或者立即返回一个$q.reject
或$q.resolve
。 I have edited your code and added return
before $q.reject
.我已经编辑了您的代码并在$q.reject
之前添加了return
。
postIssue: function (issue) { return getUserConfiguration() .then(function (response) { var headers = response.headers; var token = headers("X-XSRF-TOKEN"); if (token) { _cookie = token; if (issue.isValid()) { var url = _baseURL + "/api/issue/"; var data = JSON.stringify(issue); var config = { xhrFields: { withCredentials: true }, headers: { "X-XSRF-TOKEN": _cookie } }; return $http.post(url, data, config); } else { return $q.reject("Issue doesn't have valid fields to submit"); } } else { return $q.reject("There is no XSRF token on response header"); } }, function (error) { return $q.reject("Error getting user's configuration"); }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.