如何使JS堆栈真正“等待”为了结束异步功能?
我正在学习异步JavaScript的工作原理,并且正在尝试将数字1和2(按此顺序)打印出来。 logs 1具有settimeout的功能,因此,该顺序始终倒置。我知道为什么会发生这种情况。我只是不知道如何使它按照我的意愿工作。我已经尝试过:
function first(){
setTimeout(
()=>console.log(1),
1000
)
return Promise.resolve(true)
}
function second(){
console.log(2)
}
function a(){
first()
.then(second())
}
console.log("running...")
a()
还有:
async function first(){
setTimeout(
()=>console.log(1),
2000
)
return true
}
function second(){
console.log(2)
}
async function a(){
await first()
second()
}
console.log("running...")
a()
这两种打印
running...
2
1
所需的输出都将是
running...
1
2
我做错了什么?
I'm learning how Asynchronous JavaScript works, and I'm trying to print to the console the numbers 1 and 2 (in this order). The function that logs 1 has a setTimeout, and as such, the order is always inverted. I know why this happens. I just don't know how to make it work as I would like to. I've tried this:
function first(){
setTimeout(
()=>console.log(1),
1000
)
return Promise.resolve(true)
}
function second(){
console.log(2)
}
function a(){
first()
.then(second())
}
console.log("running...")
a()
and also this:
async function first(){
setTimeout(
()=>console.log(1),
2000
)
return true
}
function second(){
console.log(2)
}
async function a(){
await first()
second()
}
console.log("running...")
a()
Both of which print
running...
2
1
The desired output would be
running...
1
2
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
回调是不可接受的吗?
Would callbacks not be acceptable?
阅读有关JS Promises的了解( )在这里他的代码工作
Read about Js promises (developer.mozilla.org) here his your code working
谢谢你们的反馈。我向您的答案投票,因为他们俩都帮助我解决了这个问题,并帮助我对手头上的问题有了更高的了解(但是因为我在这里仍然是新手,所以upvote就像一个承诺一样)。
但是,我觉得他们都没有进入引起问题的具体点。
这是现在注释的工作代码
,没有回调
Thank you guys for your feedback. I upvoted your answers as they both helped me solve this issue, and helped me get to a higher understanding of the matter at hand (but because I'm still new here, the upvote is just like a Promise).
However, I feel like none of them has gotten to the SPECIFIC point that was causing the issue.
Here's the commented working code
Now, without callback