Promise是用来处理异步的一种方案
具体代码如下
new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
},2000)
}).then(() => {
console.log('我是then里面的settimeout');
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 3000)
}).then(() => {
console.log('我是第二个then');
})
})
另外一种处理方式
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('resolve message')
// reject('reject message')
},1000)
}).then(data => {
console.log(data);
}, err => {
console.log(err);
})
当然也有简写
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('aaa')
}, 1000)
}).then(res => {
console.log(res, '第一层');
return res + 111
}).then(res => {
console.log(res, '第二层');
return res + 222
}).then(res => {
console.log(res);
})
Promise的all
Promise.all([
new Promise((resolve, reject) => {
setTimeout(() => {
resolve({name: 'hylls', age: 29})
}, 1000)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
resolve({name: 'kobe', age: 38})
},3000)
})
]).then(results => {
console.log(results);
})
当两个异步操作都解决时 才可以调用