.then
,.catch
和.finally
是否在注册后立即进入JS事件循环(当JS运行时解释适当的代码时)?
此问题的理论面较少:
我有以下代码(链接到JSBin (online JS execution environment)]
l = console.log const g = (title) => { return (a) => { l(title + a) return a+1; } }; const gA = g("A ") const gB = g("B ") const throwError = (title) => { return (a) => { l(title + a) throw new Error("Error from promise " + title + a) } }; promise = new Promise((resolve, reject) => { resolve(1) }) l("Started application") promise .then(gA) .then(gA) .then(throwError("A ")) .catch(err => { l(err.message); }) promise .then(throwError("B ")) .then(gB) .then(gB) .catch(err => { l(err.message); }) l("Finish main function")
解析为控制台中的以下输出
"Started application" "Finish main function" "A 1" "B 1" "A 2" "A 3" "Error from promise A 3" "Error from promise B 1"
如果将按注册的顺序执行promise回调,我希望
"Error from promise B 1"
在此输出中会更高。但是它们最终出现了。 为什么会这样?
。then,.catch和.final在注册后立即(在JS运行时解释适当的代码时)立即落入JS Event Loop中还是以其他方式有所不同? ......>
.then
,.catch
和.finally
是否在注册后立即落入JS事件循环中或以其他方式不同?
[当您呼叫resolve()
时,承诺完成/拒绝被排队到承诺微任务队列中。然后,当任务开始运行时,附加到promise
根据您共享的代码,在下面说答A: