We know that JavaScript is no way to block, all the waiting can only be done through callbacks, which caused the problem of callback nesting, resulting in code chaos to burst
For a common example, a validation problem, the UID in the local cookie, get a key from server A, then get token from Server B, and eventually get the token to server C to get the user's information
Here are three API interfaces, respectively
Get key interface
var apikey= ' http://a.api.example.com/getkey?uid={uid} '
//Get token
var apitoken = ' http:// B.api.example.com/gettoken?key={key} '
//Get user information
var apiuserinfo = ' Http://a.api.example.com/getuserinfo? Token={token}&uid={uid} '
var uid = 1;
The code could be like this
$.getjson (apikey,{
' uid ': UID
},function (data) {
$.getjson (apitoken,{
' key '): Data.key
},function (data) {
$.getjson (apiuserinfo,{
' token ':d ata.token,
' uid ': Uid
}, function (user) {
alert (User.Name)})})
;
This code layer is completely impossible to see, there is no semantic effect, the latter maintenance up the head big AH
Let's just say we can write code like this.
$.getjson (apikey,{
' uid ': Uid
}). Then (function (data) {return
$.getjson (apitoken,{
' key ':d Ata.key
});
}). Then (function (data) {return
$.getjson (apiuserinfo,{
' token ':d ata.token,
' uid ': Uid
})
}). Then (function (user) {
alert (user.name)
})
Step by step down, conditioning very clear
So we have to have code to support this type of writing, of course, the great God has already written, let's take a look at
New Promise (function (resolve,reject) {
$.getjson (apikey,{
' uid ': UID
},function (data) {
Resolve (data);
},function (err) {
reject (err))
}). Then (function (data) {
new Promise (function (resolve,reject) {
$.getjson (apitoken,{
' key ':d Ata.key
},function (data) {
resolve (data)})}
). Then (XXXXX)
It looks good. Oh, we'll write a function with a callback, and we can go through the new promise.
Of course, jquery has achieved its own way. Done but this thing has been abandoned by everyone,
But this thing is too inconsistent with the promise rules, so dumping
Professional promise dedicated to jquery out of the solution
Like this.
https://www.promisejs.org/
Here's a realization, or a good one, github the most attention
And he's given a solution specifically for jquery.
Promise.resolve ($.getjson (apikey,{
' uid ': Uid
}). Then (function (data) {return
promise.resolve ($. Getjson (apitoken,{
' key ':d ata.key
})
}). Then (function (data) {return
promise.resolve ($.getjson ( apiuserinfo,{
' token ':d ata.token,
' uid ': UID
});
Then (function (user) {
alert (user.name);
});
It's even more fun.
New skills, everybody get up quickly