V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
2ME
V2EX  ›  Node.js

新手问一下关于异步返回值的问题

  •  
  •   2ME · Apr 24, 2020 · 5237 views
    This topic created in 2194 days ago, the information mentioned may be changed or developed.

    因为项目用到 puppeteer 库要写一点 Node.js 代码
    大概是 endpoint 调用 logic 的 do
    do 里需要用到 aboutPuppeteerMethod 的返回值
    但是没等到 aboutPuppeteerMethod 执行完返回 sth 已经先执行了 next
    我理解的 async 类似于 golang 的 go 关键字 但是似乎没有找到 channel 配套
    想达到在 aboutPuppeteerMethod 增加一个 channel 阻塞等待返回值继续执行后面代码的效果
    不知道该怎么写 原来没写过 js 轻喷

    function Logic() {}
    
    Logic.prototype.do = function (param) {
      var sth = aboutPuppeteerMethod()
    
      var ok = next(sth, param)
    
      return ok
    }
    
    async function aboutPuppeteerMethod() {
      ....
      await page.goto()
    
      return sth
    }
    
    
    wildnode
        1
    wildnode  
       Apr 24, 2020   ❤️ 1
    Logic.prototype.do = async function (param) {
    var sth = await aboutPuppeteerMethod()
    var ok = next(sth, param)

    return ok
    }
    royan
        2
    royan  
       Apr 24, 2020   ❤️ 1
    用 await 来阻塞等待 async
    2ME
        3
    2ME  
    OP
       Apr 24, 2020
    @wildnode 谢谢 我已经找到办法了 一开始我是这么写 但是外层 endpoint 没有这么写 所以 client 才获取不到返回值 感谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5934 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 06:38 · PVG 14:38 · LAX 23:38 · JFK 02:38
    ♥ Do have faith in what you're doing.