promise用来处理异步代码 Promise的构造函数接收一个参数,是函数,并且传入两个参数:resolve,reject,分别表示异步操作执行成功后的回调函数和异步操作执行失败后的回调函数。按照标准来讲,resolve是将Promise的状态置为fullfiled,reject是将Promise的状态置为rejected。
function getData() {
setTimeout(function () {
var name = 'tom';
return name;
}, 1000)
}
console.log(getData()); // undefined; 一开始以为能获取到tom 异步
使用回调方法 获取异步方法里面的数据
function getData1(callback) {
setTimeout(function () {
var name = 'tom';
callback(name);
}, 1000)
}
getData1(function (val) {
console.log(val); // tom
});
使用promise方法 获取异步方法里面的数据
//使用promise方法 获取异步方法里面的数据
var p = new Promise((resolve, reject) => {
setTimeout(function () {
var count = 0;
if (count) {
resolve(count);
} else {
reject(count);
}
}, 1000)
});
p.then(res => { //异步调用
console.log(res);
}, err => {
console.log(err)
})
console.log(1); //比then先执行,也就证明then是异步调用
then链式调用
//then链式调用
p.then(res => {
console.log(res);
return new Promise((resolve, reject) => {
resolve('需再return promise对象,才能继续then调用')
})
})
.then(res => {
console.log(res) // 需要return p.....
})
err & catch 谁会捕捉reject?
p.then(res => {
}, err => {
// 当同时存在,会直接走then的err回调函数, catch不执行
console.log('then的', err);
}).catch(err => {
console.log('cathc的', err);
})
promise对象提供了then,catch, all, race方法
1.all方法的传递参数需要是数组;
2.all方法的所有promise是并发执行(同时执行);
3.任何一个promise返回reject,就会中断去执行catch
promise.all()是将所有的参数接口都调用 返回出结果后再返回 并且按照参数顺序返回结果数组
promise.race()是异步调用 哪个接口返回值快 就返回哪个接口的数据