如何从异步函数返回吸引力

发布于 2025-01-20 02:24:57 字数 977 浏览 5 评论 0原文

我需要返回吸引力 https:///www.npmjs .com/package/web3核 - 促进)来自async函数。但是我总是在处理程序上没有没有的普通。这是测试代码: const web3promivent = require('web3-core-promievent')

async function sleep() {
    return new Promise((resolve) => setTimeout(resolve, 1000))
}

async function inner() {
    const pe = new Web3PromiEvent()

    await sleep()

    pe.eventEmitter.emit('done', 'ok')
    pe.resolve('ok')

    return pe
}

async function main() {
    const pe = inner()

    pe.on('done', console.log)

    const res = await pe
    console.log(res)
}

main()

这里的示例: https://codesandbox.io/s/node-js-forked-lw19bp?file=/src/index.js

async功能?

I need to return PromiEvent (https://www.npmjs.com/package/web3-core-promievent) from async function. But I always got a common Promise without on handlers. Here is the test code:
const Web3PromiEvent = require('web3-core-promievent')

async function sleep() {
    return new Promise((resolve) => setTimeout(resolve, 1000))
}

async function inner() {
    const pe = new Web3PromiEvent()

    await sleep()

    pe.eventEmitter.emit('done', 'ok')
    pe.resolve('ok')

    return pe
}

async function main() {
    const pe = inner()

    pe.on('done', console.log)

    const res = await pe
    console.log(res)
}

main()

Here the example in sandbox: https://codesandbox.io/s/node-js-forked-lw19bp?file=/src/index.js

How properly return PromiEvent from async function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文