首先我们要创建 Promise 对象
function runAsync() {
var p = new Promise(function(resolve, reject) {
//做一些异步操作
setTimeout(function() {
console.log('执行完成');
resolve('随便什么数据1');
reject('随便什么数据2')
}, 2000);
});
return p;
}
resolve为成功的 回调 reject为失败的回调
下面举个 最简单的例子
function getNumber() {
var p = new Promise(function(resolve, reject) {
//做一些异步操作
setTimeout(function() {
var num = Math.ceil(Math.random() * 10); //生成1-10的随机数
if (num <= 5) {
resolve(num);
} else {
reject('数字太大了');
}
}, 2000);
});
return p;
}
getNumber()
.then(function(data) {
console.log('resolve');
console.log(data);
console.log(somedata); //此处的somedata未定义
})
.catch(function(reason) {
console.log('reject');
console.log(reason);
});
.then 其实就是第一个回调函数
.catch 其实可以当作第二个回调函数 但是这个catch 还有一个功能就是抛出错误
实际应用中 then充当正常回调 catch充当 异常处理就好了
下面进入 重点 解决无限回调
getNumber()
.then(function(data) {
console.log(data);
return 1;
})
.then(function(data) {
console.log(data);
return 2;
})
.then(function(data) {
console.log(data);
});
.then 这里可以把 返回值传入下一个 .then
当然 如果返回值是异步的话 必须用Promise对象 当作返回值 在Promise对象里面进行参数处理
all的用法
// all 的用法
function runAsync1() {
var p = new Promise(function(resolve, reject) {
//做一些异步操作
setTimeout(function() {
console.log('异步任务1执行完成');
resolve('随便什么数据1');
}, 1000);
});
return p;
}
function runAsync2() {
var p = new Promise(function(resolve, reject) {
//做一些异步操作
setTimeout(function() {
console.log('异步任务2执行完成');
resolve('随便什么数据2');
}, 2000);
});
return p;
}
function runAsync3() {
var p = new Promise(function(resolve, reject) {
//做一些异步操作
setTimeout(function() {
console.log('异步任务3执行完成');
resolve('随便什么数据3');
}, 2000);
});
return p;
}
Promise
.all([runAsync1(), runAsync2(), runAsync3()])
.then(function(results) {
console.log(results);
});
这里的返回结果将会 等到三个函数执行完成后 统一返回一个 数组
race的用法
Promise
.all([runAsync1(), runAsync2(), runAsync3()])
.then(function(results){
console.log(results);
});
返回执行快的一个