ES9(二) —— Promise.finally

JavaScriptES6

# Promise是如何“兜底”操作的?

使用Promise.finally,无论执行then还是catch,都会执行finally里面的函数体。 ​ 例如一个弹窗:可以用resolvereject分别保存变量的值, 但是最后用finally去控制弹窗的弹出。 ​ 下面看代码的例子:

const Gen = (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if(time < 500) {
        reject(time)
      } else {
        resolve(time)
      }
    }, time);
  })
}Gen(Math.random() * 1000)
  .then(val => console.log(val))
  .catch(err => console.log(err))
  .finally(() => {console.log('finish') })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
更新时间: 2021-09-15 12:03