群友出了一道 JS 异步顺序题😫

208 天前
 xyxsw2023
const async1 = async (resolve) => {
    console.log("async1 start")
    await async2()
    resolve()
    console.log("after resolve")
}

const async2 = async () => {
    console.log("async2")
}

console.log("after func define")

setTimeout(()=>{
    console.log("set timeout")
},0)

new Promise(async (resolve)=>{
    await async2()
    console.log("promise running")
    async1(resolve)
    console.log("promise end")
}).then(()=>{
    console.log("then start")
    setTimeout(()=>{
        console.log("timeout trigger")
    },0)
})

console.log("script end")
1770 次点击
所在节点    JavaScript
13 条回复
weject
208 天前
毫无意义
agagega
208 天前
NodeJS 跑出来的结果:
after func define
async2
script end
promise running
async1 start
async2
promise end
after resolve
then start
set timeout
timeout trigger
mcfog
208 天前
开飞机是不是得自己会飞啊
yuankui
207 天前
茴香豆的茴写出来新高度
yagamil
207 天前
算是 js 的事件循环的基础题吧。 不难
learningman
207 天前
有的顺序其实不是语法规定,而是 v8 实现特定的,这种这。也要管吗
LiTangDingZhen
207 天前
Event Loop?
shuimugan
207 天前
没啥意义,敢这么写的都让我打回去用正规 async function 写法了。
IDE 的坏味道告警出题人真不看是吧,async function 里面不用 await 的话,函数为啥不去掉 async 。
setTimeout 换成 const setTimeout = require('timers/promises').setTimeout 保平安。

以前面试 PHP 技术管理时,也碰到过 PHP 里类似题目,我就写了几个代码里出现能勉强容忍的,剩下的写"不回答,在团队里敢这么写的都会被打回去重写"。然后一面时告诉我,我的笔试题是历史上最高分的。
Opportunity
207 天前
@shuimugan
> async function 里面不用 await 的话,函数为啥不去掉 async

这个我知道为什么
https://typescript-eslint.io/rules/promise-function-async/
chegde
207 天前
面试题得考这个
hitsmaxft
206 天前
没啥意思,不 await 的 promise 就是入队背景执行呗。
这么写很容易出现 bug ,正常代码禁止这么干的
lyxxxh2
189 天前
我还以为是语音播报的场景
比如: "微信" "收款" "一" "百" "元" ,5 个音频文件顺序播放
这个看得我懵逼...
RainChen128
57 天前
明天要面试了,特地找回来这个几百天前看到的史帖子复习一下,挺绕的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/981873

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX