V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
2ME
V2EX  ›  Node.js

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

  •  
  •   2ME · 2020-04-24 11:43:22 +08:00 · 4750 次点击
    这是一个创建于 1487 天前的主题,其中的信息可能已经有所发展或是发生改变。

    因为项目用到 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  
       2020-04-24 11:57:28 +08:00   ❤️ 1
    Logic.prototype.do = async function (param) {
    var sth = await aboutPuppeteerMethod()
    var ok = next(sth, param)

    return ok
    }
    royan
        2
    royan  
       2020-04-24 12:01:36 +08:00   ❤️ 1
    用 await 来阻塞等待 async
    2ME
        3
    2ME  
    OP
       2020-04-24 12:02:07 +08:00
    @wildnode 谢谢 我已经找到办法了 一开始我是这么写 但是外层 endpoint 没有这么写 所以 client 才获取不到返回值 感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2068 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:16 · PVG 08:16 · LAX 17:16 · JFK 20:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.