Я пытался понять, как await
работает в разных сценариях, и столкнулся с проблемой.
new Promise(async (resolve, reject) => {
resolve();
console.info(await Promise.resolve(7))
console.info(8)
}).then(() => console.info(3))
этот код регистрирует 7, 8, 3
- поэтому он не помещает console.info в очередь микрозадач. (вот чего я не понимаю.
Итак, я попытался переписать строку await
на синтаксис Promise:
new Promise(async (resolve, reject) => {
resolve();
const pr = new Promise((res) => {
res(7)
})
pr.then((num) => console.info(num))
console.info(8)
}).then(() => console.info(3))
Но теперь он помещает then
в очередь микрозадач и журналирует 8
первым.
Журналы: 8, 7, 3
.
Вопрос: почему моя попытка воссоздать console.info(await Promise.resolve(7))
некорректна?
Почему await Promise.resolve() выполняется немедленно?
Правило простое: await
помещает весь код под ним и все, что находится за пределами его выражения в своей строке, в микрозадачу:
<script type = "module">
console.info ( ( await Promise.resolve({name: 'John'}) ).name );
// ------------------------------- this is executed sync (first)
// -------------- ------- this is executed in the created microtask
// all the code below is executed also in the created microtask
</script>
Итак, ваш console.info(8)
действительно помещен в микрозадачу, но, как вы можете проанализировать, он ставится последним в первой микрозадаче.
new Promise(async (resolve, reject) => {
resolve();
console.info(await Promise.resolve(7)) // await puts both the console.info's into the first microtask
console.info(8)
}).then(() => console.info(3)) // then puts the callback into the second microtask
Давайте немного изменим, чтобы узнать больше, как это работает:
<script type = "module">
new Promise((resolve, reject) => {
resolve();
}).then(() => console.info(3)) // then puts the callback into the first microtask
await 1; // puts the below code into the second microtask
console.info(await Promise.resolve(7)) // both the console.info's are put into the third microtask
console.info(8)
</script>
new Promise(async ...
НИКОГДА не является хорошим «образцом» — независимо от того, что вы делаете после этого