ghostgril
V2EX  ›  问与答

es6 里面的 promise 里的 return 是做什么的呢

  •  
  •   ghostgril · Apr 18, 2018 · 4052 views
    This topic created in 2947 days ago, the information mentioned may be changed or developed.

    promise 只能返回一个 promise 对象,但是我总是看到一些书本和 GitHub 的代码 return 加上一个返回值的。这是为何?

    9 replies    2018-04-24 08:03:49 +08:00
    ghostgril
        1
    ghostgril  
    OP
       Apr 18, 2018
    return value 和 resolve(value)的区别在哪里呢
    grantonzhuang
        2
    grantonzhuang  
       Apr 18, 2018 via Android
    传给 then 的函数内返回的值会传给传给下一个 then 的函数
    grantonzhuang
        3
    grantonzhuang  
       Apr 18, 2018 via Android
    @grantonzhuang 绕口。。。
    grantonzhuang
        4
    grantonzhuang  
       Apr 18, 2018 via Android
    @ghostgril 传给 then 的函数内没有 resolve
    murmur
        5
    murmur  
       Apr 18, 2018
    return Promise.resolve(xxx)了解下朋友
    ghostgril
        6
    ghostgril  
    OP
       Apr 18, 2018
    @grantonzhuang 就是 promise 里面返回值使用 resolve,使用 return 无效?然后 then 里面使用 return 传给下一个 then 的意思
    ghostheaven
        7
    ghostheaven  
       Apr 19, 2018 via Android
    then 和 catch 中返回 promise,会在这个 promise resolve 或 reject 的时候,把 resolve 或 reject 的结果作为参数传给后面的 then 或 catch。
    如果返回普通类型的值,就直接作为参数传给下一个 then。
    ghostgril
        8
    ghostgril  
    OP
       Apr 23, 2018
    @ghostheaven 这个 promise 里 return 会如何呢?就是不执行后面的代码了吗
    ghostheaven
        9
    ghostheaven  
       Apr 24, 2018 via Android   ❤️ 1
    @ghostgril 函数内任何位置 return 都会结束当前函数,不再继续之后的语句,不知道你想问的是不是这个。对于 promise 也是一样,不过结束返回后 JS 引擎会回调下一个 then 里的函数,并把返回值作为参数传过去,其实你可以使用 setTimeout 自己实现一个类似 Promise 的行为。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5775 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 66ms · UTC 06:29 · PVG 14:29 · LAX 23:29 · JFK 02:29
    ♥ Do have faith in what you're doing.