使用Promise.finally
,不管執行then
仍是catch
,都會執行finally
裏面的函數體。編程
例如一個彈窗:能夠用resolve
和reject
分別保存變量的值,
可是最後用finally
去控制彈窗的彈出。segmentfault
下面看代碼的例子:dom
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') })