先通过刷题熟悉下Promise的基本用法

01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var first = () => (new Promise((resolve, reject) => {
console.log(3);
let p = new Promise((resolve, reject) => {
console.log(7);
setTimeout(() => {
console.log(5);
resolve(6);
}, 0)
resolve(1);
});
resolve(2);
p.then((arg) => {
console.log(arg);
});
}));
first().then((arg) => {
console.log(arg);
});
console.log(4);

// 3 7 4 1 2 5

02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('once')
resolve('success')
}, 1000)
})

const start = Date.now()
promise.then((res) => {
console.log(res, Date.now() - start)
})
promise.then((res) => {
console.log(res, Date.now() - start)
})
// once
// success 1001
// success 1001

03

1
2
3
4
5
6
7
8
9
10
11
12
Promise.resolve()
.then(() => {
return new Error('error!!!')
})
.then((res) => {
console.log('then: ', res)
})
.catch((err) => {
console.log('catch: ', err)
})
// then Error: error!!!
// at <anonymous>

.then 或者 .catch 中 return 一个 error 对象并不会抛出错误,所以不会被后续的 .catch 捕获,需要改成其中一种:

  • return Promise.reject(new Error(‘error!!!’))
  • throw new Error(‘error!!!’)

因为返回任意一个非 promise 的值都会被包裹成 promise 对象,即 return new Error(‘error!!!’) 等价于 return Promise.resolve(new Error(‘error!!!’))

04

1
2
3
4
5
6
7
8
9
10
11
Promise.resolve()
.then(function success (res) {
throw new Error('error')
}, function fail1 (e) {
console.error('fail1: ', e)
})
.catch(function fail2 (e) {
console.error('fail2: ', e)
})
// fail2: Error: error
// at success (<anonymous>:3:11)

05

请实现一个mergePromise函数,把传进去的数组按顺序先后执行,并且把返回的数据先后放到数组data中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const timeout = ms => new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, ms);
});

const ajax1 = () => timeout(2000).then(() => {
console.log('1');
return 1;
});

const ajax2 = () => timeout(1000).then(() => {
console.log('2');
return 2;
});

const ajax3 = () => timeout(2000).then(() => {
console.log('3');
return 3;
});

const mergePromise = ajaxArray => {
// 在这里实现你的代码
};

mergePromise([ajax1, ajax2, ajax3]).then(data => {
console.log('done');
console.log(data); // data 为 [1, 2, 3]
});