为什么要达到此输出?
谁能告诉我为什么这段代码会输出以下内容?我完全迷失在异步函数上,几乎要放弃了。
第一个等待按照我的预期执行,并在执行前等待 1 秒。然而,不知怎的,301 是在执行之前在 then
之前输出的,这似乎完全违背了 then
的字面定义。 Done 被输出,然后以某种方式返回并执行第二个 then 语句。
async function test() {
const promise1 = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
console.log('First await executed')
}, 1000)
}).then(() => {
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
console.log("This was executed")
}, 1000)
})
}).then(() => Promise.resolve(301));
console.log(promise1)
await setTimeout(() => console.log(1000), 1000)
console.log("Done");
}
test()
Can anyone tell me why this code outputs the following? I am completely lost on async functions and close to just giving up.
The first await does what I expect and waits 1 second before executing. However, somehow 301 is outputted before the then
before it is executed which seems to completely defy the literal definition of then
. Done is outputted then somehow it goes back and executes the second then statement.
async function test() {
const promise1 = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
console.log('First await executed')
}, 1000)
}).then(() => {
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
console.log("This was executed")
}, 1000)
})
}).then(() => Promise.resolve(301));
console.log(promise1)
await setTimeout(() => console.log(1000), 1000)
console.log("Done");
}
test()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论