gpt4 book ai didi

javascript - 如何获得 $http API 调用的 promise

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

我想在不编写任何服务的情况下获得异步调用的 promise 。我已经编写了一些API来用JavaScript从后端获取数据,但是以下代码没有编写在任何服务中。我想在另一个 JavaScript 文件中访问以下 promise 。如何访问不同文件中的 promise ?

  var cust_Promise = $q.defer() ;    
var apt_data={some data};
$http.post(api,apt_data)
.success(function (response,status) {
cust_Promise.resolve('Success');
return cust_Promise.promise ;
}) ;

最佳答案

$http 服务返回 promise 。

只需保存返回的 promise 即可。

var apt_data = {some data};

var promise = $http.post(url, apt_data);

这意味着 AngularJS 框架支持将它们传递给其他函数,将它们作为其他函数的值返回,并将它们分配给变量或将它们存储在数据结构中。

可以使用标准的.then.catch方法检索已完成的结果或拒绝的错误信息。

var derivedPromise = promise.then (function onfullFilled(response) {
$scope.data = results.data;
//return for chaining
return response;
}).catch ( function onRejected(response) {
console.log(response.statusText);
//throw to chain rejection
throw response;
});

由于调用 Promise 的 .then 方法会返回一个新的派生 Promise,因此可以轻松创建 Promise 链。可以创建任意长度的链,并且由于一个 Promise 可以用另一个 Promise 来解决(这将进一步推迟其解决),因此可以在链中的任何点暂停/推迟 Promise 的解决。这使得实现强大的 API 成为可能。 1

来自文档:

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

General usage:2

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the error callback will not be called for such responses.

其他资源

关于javascript - 如何获得 $http API 调用的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35668858/

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