随着ES6的推行它的许多新特性受到了广大开发者的好评,比如promise,为什么使用这个promise呢,他具体能帮我们做些啥?
其实从字面意思上来理解promise
就是承诺,比如:你命令你的手下本月推销100台产品,他回复没问题百分百完成任务;在这个时候你得到的最终结果就是一个承诺。
还是从案例来理解哈比较清楚;
一、 传统的方法获取多个api异步回调的结果
var user = {
getUserID: function (succCallback, failCallback) {
$.ajax({
type: "POST",
url: "",
data: {},
headers: {},
success: function (response) {
succCallback && succCallback(response);
},
error: function (err) {
failCallback && failCallback(err)
}
});
},
getUserName: function (id, succCallback, failCallback) {
$.ajax({
type: "POST",
url: "",
data: {
id: id
},
headers: {},
success: function (response) {
succCallback && succCallback(response);
},
error: function (err) {
failCallback && failCallback(err)
}
});
},
getUserInfo: function (name, succCallback, failCallback) {
$.ajax({
type: "POST",
url: "",
data: {
name: name
},
headers: {},
success: function (response) {
succCallback && succCallback(response);
},
error: function (err) {
failCallback && failCallback(err)
}
});
},
// 看这个调用是否有点老火
getUserData: function (succCallback, failCallback) {
this.getUserID(isRes => {
this.getUserName(isRes, nameRes => {
this.getUserInfo(nameRes, response => {
succCallback && succCallback(response);
}, err => {
failCallback && failCallback(err)
})
}, err => {
})
}, err => {
})
}
}
module.exports = user;
二、 使用promise获取多个api异步回调的结果
var user = {
getUserID: function () {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: "",
data: {},
headers: {},
success: function (response) {
resolve(response);
},
error: function (err) {
reject(err)
}
});
})
},
getUserName: function (id) {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: "",
data: {
id: id
},
headers: {},
success: function (response) {
resolve(response);
},
error: function (err) {
reject(err)
}
});
})
},
getUserInfo: function (name) {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: "",
data: {
name: name
},
headers: {},
success: function (response) {
resolve(response);
},
error: function (err) {
reject(err)
}
});
})
},
// 这个调用是否看起来要更清晰一点
getUserData: function () {
return new Promise((resolve, reject) => {
this.getUserID().then(resID => {
return this.getUserName(resID);
}).then(resName => {
return this.getUserInfo(resName);
}).then(res => {
resolve(res);
}).catch(err => {
reject(err);
})
})
},
// 另一种调用
/* getUserData: function () {
return new Promise((resolve, reject) => {
this.getUserID().then(resID => {
this.getUserName(resID).then(resName => {
this.getUserInfo(resName).then(res => {
resolve(res);
}).catch(err => {
reject(err)
})
}).catch(err => {
})
}).catch(err => {
})
})
}
*/
}
module.exports = user;
个人理解使用promise
就是:我们不用再自己写callback回调来获取异步操作后的结果了(理解不正确的欢迎指正)