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

2020-04-24 11:43:22 +08:00
 2ME

因为项目用到 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
}

4755 次点击
所在节点    Node.js
3 条回复
wildnode
2020-04-24 11:57:28 +08:00
Logic.prototype.do = async function (param) {
var sth = await aboutPuppeteerMethod()
var ok = next(sth, param)

return ok
}
royan
2020-04-24 12:01:36 +08:00
用 await 来阻塞等待 async
2ME
2020-04-24 12:02:07 +08:00
@wildnode 谢谢 我已经找到办法了 一开始我是这么写 但是外层 endpoint 没有这么写 所以 client 才获取不到返回值 感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/665621

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX