场景:两个ajax异步请求的返回值作为另外一个函数的参数,不使用嵌套,如何保证函数能接受到参数,并且做到以最长运行ajax的时间为另外一个函数接收到的时间。
两种实现方法:
Promise对象
async函数
Promise对象
// Promise对象
function a(resolve, reject) { // 将promise对象的参数传过来
return $.ajax({
url: 'https://127.0.0.1:8009/info',
type: "post",
data: {title: 'tttt', content: 'ggggg', faceId: 'ddasfasf-646-asff'},
dataType: 'json',
success: function (data) {
if (data.code === 200) {
console.log(data);
resolve(data); // 请求成功后,利用resolve改变promise状态,并且作为返回值传回到promise对象
} else {
reject(data); // 请求失败则利用reject改变状态,终止当前函数流
}
}, error: function (data) {
console.log("错误" + data);
}
});
}
// 创建新promise实例
const _ajax1 = new Promise(function (resolve, reject) {
a(resolve, reject);// 将resolve和reject传过去
});
const _ajax2 = new Promise(function (resolve, reject) {
a(resolve, reject);// 将resolve和reject传过去
});
// 注意,这里一定是要传一个‘数组’或者其他具有Iterator的数据结构
/*
Array
Map
Set
String
TypedArray
函数的 arguments 对象
NodeList 对象
*/
Promise.all([_ajax1, _ajax2])
.then(result => console.log(result)) // 此处打印的就是a函数中ajax请求成功后resolve出来的值
.catch(err => console.log(err)) // 异常处理
async函数
// async函数
function a() {
return $.ajax({
url: 'https://127.0.0.1:8009/info',
type: "post",
data: {title: 'tttt', content: 'ggggg', faceId: 'ddasfasf-646-asff'},
dataType: 'json',
success: function (data) {
if (data.code === 200) {
console.log(data);
} else {
console.log('error:' + data);
}
}, error: function (data) {
console.log("错误" + data);
}
});
}
async function _ajax() {
let result = await a();
let result1 = await a();
// 这里会等result和result1运行完毕
if (result && result1) {
console.log('entered');
console.log(result);
console.log(result1);
}
return result;
}
_ajax();