前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >nodejs async 测试

nodejs async 测试

原创
作者头像
shirishiyue
修改2023-05-25 09:32:47
2280
修改2023-05-25 09:32:47
举报
文章被收录于专栏:全栈码全栈码

async 测试一个:当await一个async函数时,只await这个函数的一部分,另一部分不await

代码语言:typescript
复制
    async function entrance(type: string, handler: any, ...args: string[]) {
        console.log(moment().unix(), '11111 entrance start');
        await wait(2000);
        return handler(...args);
    }

    async function type1Func() {
        console.log(moment().unix(), '11111 type1Func start');
        const r = await wait(5000);
        console.log(moment().unix(), '11111 type1Func end');
        return 1;
    }

测试几种调用方式:

代码语言:typescript
复制
await entrance('type1Func', type1Func)
await entrance('type1Func', () => type1Func())   // 和下面一样
await entrance('type1Func', () => {return type1Func()}) // 和上面一样
await entrance('type1Func', () => {type1Func()})


// Main function
    console.log(moment().unix(), '11111 main process start');
    const r = await entrance('type1', wrapFunc); // 先测试第1种,再换第4种。
    console.log(moment().unix(), '11111 main process end', r);

第1种结果:

代码语言:txt
复制
1683690391 11111 main process start
1683690391 11111 entrance start
1683690393 11111 type1Func start
1683690398 11111 type1Func end
1683690398 11111 main process end 1

第4种结果:

代码语言:txt
复制
1683690434 11111 main process start
1683690434 11111 entrance start
1683690436 11111 type1Func start
1683690436 11111 main process end undefined
1683690441 11111 type1Func end

结论是:当不在乎async函数返回结果时,通过 () => { type1Func() } 可以变成normal函数了,执行完就走,不会await。如果需要返回结果,这样 () => { return type1Func() } 那还是会await等待。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • async 测试一个:当await一个async函数时,只await这个函数的一部分,另一部分不await
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档