Man957
V2EX  ›  前端开发

promise 相关问题

By Man957 at 2024 年 1 月 10 日 · 1310 次点击

Promise.resolve().then(() => { throw new Error('abc') }); // Return new Promise(resolve => resolve(Promise.reject(new Error('abc')))) 为啥这两个结果等同?第二个 promise 是如何进行执行的?

4 条回复  •  2024-01-29 17:35:15 +08:00
Cat7373
   1
Cat7373  
   2024 年 1 月 16 日
我帮你整理下格式:


Promise.resolve().then(() => {
   throw new Error('abc')
});


new Promise(resolve =>
   resolve(Promise.reject(new Error('abc')))
);
MinonHeart
   2
MinonHeart  
   2024 年 1 月 23 日
https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md

Fulfilled, if it has been resolved to a non-promise value, or resolved to a thenable which will call any passed fulfillment handler back as soon as possible, or resolved to another promise that is fulfilled.

Rejected 也是一样的逻辑。

执行 Promise.reject(new Error('abc'))
得到 Promise<Error>
执行 resolve ,跳到外层的 Promise
返回 Promise<Promise<Error>>
unwrapping (用户侧不可见)
得到 Promise<Error>
supuwoerc
   3
supuwoerc  
   2024 年 1 月 29 日
then 本身就会返回一个 promise ,不写 return 的话就相当于返回了 undefined ,发生错误或者 resolve/return 了 reject 都会使得 promise 进入 rejected 状态,有 catch 的话也会进去。
supuwoerc
   4
supuwoerc  
   2024 年 1 月 29 日
@supuwoerc 说的有点乱了,promise 的构造函数传入的函数,里面调用 resove 就相当于 then 里面调用 return ,大致这样
© 2026 V2EX · 34ms · 3.9.8.5