LeungJZ
V2EX  ›  问与答

js 的 async await 说到底还是伪异步吗?

  •  
  •   LeungJZ · Apr 2, 2018 · 3716 views
    This topic created in 3139 days ago, the information mentioned may be changed or developed.

    实践基于 vue

    如下图,左边是 component 的 mounted 函数,右边是 mixin 的 mounted 函数。

    在 vue 中,mixin 的 mounted 会比 component 的先执行。

    所以我当时就想,在 mixin 中先获取数据,再交由 component 处理,因为该 mixin 在两个组件中都用上了。

    可是,事与愿违,mixin 中 await 后的函数还是会等到所有的 mounted 执行完成后才会执行的。

    那么请问一下,我该如何去调整?

    11 replies  •  2018-04-02 17:52:32 +08:00
    wwqgtxx
    wwqgtxx
    Apr 2, 2018 via iPhone
    1
    异步执行也没人说就一定是并发执行吧
    LeungJZ
    LeungJZ
    OP
    Apr 2, 2018
    2
    @wwqgtxx
    以为是 await 后的,会等返回结果再执行,原来只限于本函数。
    maichael
    maichael
    Apr 2, 2018
    3
    如果 await 后所有代码都要等返回回来再执行,那叫阻塞。

    阻塞和非阻塞,和你是异步还是不是异步一点关系都没有。
    LeungJZ
    LeungJZ
    OP
    Apr 2, 2018
    4
    @maichael
    好吧,表达错了。
    wwqgtxx
    wwqgtxx
    Apr 2, 2018 via iPhone
    5
    @LeungJZ 本质上 await 是用 switch 实现的,你可以用 babel 转码成 es5 看看就知道了,所以他的作用域局限于 async 函数内
    Yuiham
    Yuiham
    Apr 2, 2018
    6
    mixins 和组件提供的生命周期钩子会在组件初始化的时候合并成数组。但是生命周期钩子的调用是同步的顺序的,调用完第一个 mounted 后接着调用第二个。你的 mixins 提供的 mounted 里的请求响应至少得到下一轮事件循环了
    LeungJZ
    LeungJZ
    OP
    Apr 2, 2018
    7
    @Yuiham
    但是事件处理弄到 setTimeout 还是不行。
    Yuiham
    Yuiham
    Apr 2, 2018
    8
    @LeungJZ 你在组件的 created 中用 $once 监听一个事件 a,注册 callback。接着等 mixins 的 mounted 拿到响应数据,带上数据 emit 这个事件 a。这样可以干掉多余的本地状态和生命周期钩子。
    AJian
    AJian
    Apr 2, 2018
    9
    只是对语法糖而已
    catoncat
    catoncat
    Apr 2, 2018
    10
    mixin 里写成 method,然后 component 的 amounted 钩子里面 await 调用
    LeungJZ
    LeungJZ
    OP
    Apr 2, 2018
    11
    @crs0910
    这是我现在唯一能想到的解决办法。


    @Yuiham
    这个方法好像不错。我试试,谢谢了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5007 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 55ms · UTC 06:47 · PVG 14:47 · LAX 22:47 · JFK 01:47
    ♥ Do have faith in what you're doing.