V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
lithium148
V2EX  ›  问与答

请问.then()里面为什么要添加=>箭头函数

  •  
  •   lithium148 · 2020-09-02 14:22:57 +08:00 · 1876 次点击
    这是一个创建于 1304 天前的主题,其中的信息可能已经有所发展或是发生改变。

    new Promise(function (resolve) { app.onLogin(resolve); }).then(()=>this.onGetDefaultTime())

    预想执行顺序:执行 app.onLogin()完成后,执行 this.onGetDefaultTime()

    如果 then()里面是 then(this.onGetDefaultTime()) 则 2 个函数同时执行,onGetDefaultTime()不会乖乖等到前面的执行完

    改成 then(()=>this.onGetDefaultTime()) 则会正确顺序执行。

    请问为什么?

    谢谢!

    10 条回复    2020-09-02 15:01:56 +08:00
    Plutoler
        1
    Plutoler  
       2020-09-02 14:26:25 +08:00
    then 第一个参数是 onFulfilled 回调函数, 不想写箭头函数的话可以用 then(this.onGetDefaultTime) 试试

    参考: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
    AngryPanda
        2
    AngryPanda  
       2020-09-02 14:28:58 +08:00
    因为期待的是一个 function,如果你传过去的不是 function, 而是一个表达式,则会尝试执行表达式以获取返回值(这个返回值可能是个函数)。
    across
        3
    across  
       2020-09-02 14:29:35 +08:00
    前面那个加()就做了调用。

    ()=>{}是个 lambda 表达式,传过去的是个函数指针。
    lithium148
        4
    lithium148  
    OP
       2020-09-02 14:32:08 +08:00
    @Plutoler 感谢回答,这个是不是和 SetInterval(function,milliseconds)的第一个空 function 不用加括号一样
    sugars
        5
    sugars  
       2020-09-02 14:34:26 +08:00
    TomVista
        6
    TomVista  
       2020-09-02 14:34:49 +08:00
    函数() 作为参数会首先执行,

    a(b())

    会先执行 b
    在执行 a

    因为你的 a,b 有异步的,有了同时执行的错觉,

    和 Promise 无关
    mota
        7
    mota  
       2020-09-02 14:36:53 +08:00
    then 的参数类型是函数,看两种写法的类型就很清晰了,尽量不要按照括号不括号的去硬记。
    rioshikelong121
        8
    rioshikelong121  
       2020-09-02 14:40:49 +08:00
    .then(()=>this.onGetDefaultTime())

    意味着你给 then 穿了一个 resolver function 的引用,这个 function 会在前一个 promise resolve 以后调用。

    .then(this.onGetDefaultTime())

    意味着你给 then 传递了一个 this.onGetDefaultTime() 调用的结果。调用时机是同步的,一般来说比你 app.onLogin 的 callback 执行的还要早。then(resolve, reject)里面 resolve, reject 的值是可以为非函数的。这个值会被继续往 promise 链的后面传递。

    new Promise(function (resolve) { app.onLogin(resolve); }).then(()=>this.onGetDefaultTime()).then(console.log)

    应该可以打印出来这个值。
    lithium148
        9
    lithium148  
    OP
       2020-09-02 15:01:39 +08:00
    感谢以上所有回答,谢谢各位大佬
    lithium148
        10
    lithium148  
    OP
       2020-09-02 15:01:56 +08:00
    @rioshikelong121 很全面,感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3651 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:27 · PVG 18:27 · LAX 03:27 · JFK 06:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.