Cause
Everyone knows that the most troublesome thing about doing front-end development is the handling of asynchronous requests. Continue to write functions in the successful callback function of the request, which will form callback hell in the long run.
function load() {
$.ajax({
url: 'xxx.com',
data: 'jsonp',
success: function(res) {
init(res, function(res) {
render(res, function(res) {
// 一层一层又一层
});
});
}
}
}
load();
Of course, such a small code level can still be seen, but if it is more, it will be difficult to maintain. It is extremely helpless whether it is the developer or a colleague who takes over the project! What I want, what I want, what, what.
So there is a Promise
When I heard the report about Promise, I didn't pay much attention. I only knew that it was to solve the problem of callback hell, an asynchronous request solution. Later, I found that JQ has also implemented related methods in the work, and the code
$.get('xxx.php').done(function() {
alert('成功的回调'); // 相当于Promise的resolve()
});
Now it seems that it is really similar to Promise. So let’s go back to today’s protagonist
First introduce the three states of Promise:
- Pending in progress
- Fulfilled succeeded
- Rejected has failed
After talking about the status, go directly to the code, we have to know how to use it:
Also take the example of the load function above
// then方法是用的最多的了
// 按照then来执行成功和失败的回调函数
function load() {
return new Promise((resovel, reject) => {
$.ajax({
url: 'xxx.com',
data: 'jsonp',
success: function(res) {
resolve(res);
},
error: function(err) {
reject(err);
}
});
});
}
// 用一下
load().then(data => {
console.log(data); // 请求到的数据
console.log('请求数据成功');
}, err => {
console.log('请求失败');
});
In addition to processing requests, Promises can also be written in ordinary functions
function init(options) {
return new Promise((resolve, reject) => {
if (options.id) {
console.log('你是唯一')
resolve(options.id);
} else {
console.log('不行,不行');
reject()
}
});
}
init({
id: 110})
.then(id => {
console.log(id); // 110
let obj = {
id, nickname: '左夕'};
return obj;
})
.then(other => {
console.log(other); // { id: 110, nickname: '左夕' }
});
Promise.all and Promise.race are somewhat similar
all means that the status of the Promise is successful to indicate success
Race is the state of Promise. There is a state that succeeds first, which means success
Axios, which is very popular recently, actually calls Promise, and the writing is also very similar.
Since it is a third-party package, you need npm i axios to install it
// 发个get请求
axios.get('user/', {
id,
username
}).then(res => {
console.log(res); // 成功
}).catch(err => {
console.log(err); // 失败
});
// 再来个post请求
axios.post('login/', {
username,
password
}).then(res => {
console.log(res); // 成功
}).catch(err => {
console.log(err); // 失败
});
// 也有all的操作
function getUser() {
return axios.get('/user');
}
function sendMsg() {
return axios.post('/info', {
msg});
}
axios.all([getUser(), sendMsg()]).then(res => {
})
To summarize: These are the commonly used Promises, and then returns a Promise object, so you can continue to call the .then method.