问题一:我需要用第一次发送ajax请求回的数据作为第二次ajax的参数,而第二次的ajax是在第一次ajax的回调函数里发送的。但是这里有问题!就是第二次ajax返回的数据不能赋值给全局对象的属性,不知道是不是掉到坑里了。所以想用$q解决。
问题二:那这个例子来说吧,
// $q 是内置服务,所以可以直接使用
ngApp.factory('UserInfo', ['$http', '$q', function ($http, $q) {
return {
query : function() {
var deferred = $q.defer(); // 声明延后执行,表示要去监控后面的执行
$http({method: 'GET', url: 'scripts/mine.json'}).
success(function(data, status, headers, config) {
deferred.resolve(data); // 声明执行成功,即http请求数据成功,可以返回数据了
}).
error(function(data, status, headers, config) {
deferred.reject(data); // 声明执行失败,即服务器返回错误
});
return deferred.promise; // 返回承诺,这里并不是最终数据,而是访问最终数据的API
} // end query
};
}]);
deferred.resolve 是为了延迟执行吗?那如果能在回调函数里面写逻辑为什么还要多此一举的延迟执行呢?
问题三:为什么说deferred.promise返回的承诺是最终数据api?这个promise的作用是什么?
问题四:promise.then执行逻辑是什么?
Before I answer all your questions, let me briefly explain your sample code! !
Your sample code is a typical
Promise
的反面教材,其特征就是:无目的的创建deferred
object, which only increases the code complexity. Regarding this, you can see the anti-pattern here:First of all, when you realize that you are enduring
callback hell
的时候,恭喜你,在javascript
this road, you are on the right path. So what are the solutions? The ones we see most recently include:Promise
generator
Cooperate with coasync/await
Regarding the detailed introduction of these methods, I didn’t read other people’s answers carefully (maybe there are better ones), so I can only post what I wrote before. Asynchronous in JavaScript
OK, we introduced several common ways to solve
callback hell
, and let’s talk about yourcallback hell
的几种常见方式,再回头来说你的Promise
problemQuestion 1: I need to use the data returned by the first ajax request as the parameter of the second ajax, and the second ajax is sent in the callback function of the first ajax. But there's a problem! It's just that the data returned by ajax for the second time cannot be assigned to the properties of the global object. I don't know if I have fallen into a pit. So I want to use $q to solve it.
Since we hope that
works. Let me give you an example first: 4. EspeciallyPromise
能够解决回调地狱的问题,拿肯定不会再是使用回调的方式,你的疑惑是对的,可你的问题是没有充分理解Promise
can solve the problem of callback hell, we will definitely not use callbacks anymore. Your doubts are correct, but your question is that you do not fully understand howreturn call2(param1);
, really don’t nest it again (a mistake made by many players who are new to), directly Return and you will get the result in the next
Question 2: Let’s take this example
This is the first question. You overreacted and obviously complicated a simple issue. This is enough: 🎜 Where to call 🎜, just use 🎜 directly: 🎜then
The third and fourth questions are all based on a general understanding of
Promise
本身的实现没概念,我之前写过一个小教程,教大家自己手写一个Promise
的简单实现,建议你跟着做做,先对Promise
itself, and how to handwrite a Promise step by step