【问题标题】:Creating a function that returns a PromiEvent using web3-core-promievent使用 web3-core-promievent 创建一个返回 PromiEvent 的函数
【发布时间】:2019-05-17 20:19:15
【问题描述】:

我尝试运行以下 sn-p,但无济于事。

我找到了 sn-p here

var Web3PromiEvent = require('web3-core-promievent');

var myFunc = function(){
    var promiEvent = Web3PromiEvent();

    setTimeout(function() {
        promiEvent.eventEmitter.emit('done', 'Hello!');
        promiEvent.resolve('Hello!');
    }, 10);

     return promiEvent.eventEmitter;
};


// and run it
myFunc()
.then(console.log)
.on('done', console.log);

我总是遇到这种错误:TypeError: myFunc(...).then(...).on is not a function

能够有一种方法从我的函数中发出事件对我来说至关重要,这表明在函数执行期间发生了事情。如果可能的话,我更喜欢使用 async/await 语法。

我真的很想避免向函数发送回调参数,而是能够按照我认为适合代码的不同部分的方式处理事件。

【问题讨论】:

  • 你不能只做console.log(myFunc())吗?

标签: javascript events web3


【解决方案1】:

我认为您误读了文档,您可以将.on 方法链接到Web3PromiEvent 对象,但不能链接到.then 返回的Promise 对象

所以要么链接.on,要么链接.then

myFunc()
.then(console.log);

myFunc()
.on('done', console.log);

如下图所示,.then 返回的 Promise 没有附加 .on 方法,无论 Web3PromiEvent 返回的 Promise 是否有。

这是doc的原始示例

// in node.js
var Web3PromiEvent = require('web3-core-promievent');

var myFunc = function(){
    var promiEvent = Web3PromiEvent();

    setTimeout(function() {
        promiEvent.eventEmitter.emit('done', 'Hello!');
        promiEvent.resolve('Hello!');
    }, 10);

    return promiEvent.eventEmitter;
};


// and run it
myFunc()
.then(console.log); //see the semicolon
.on('done', console.log); //see the semicolon

【讨论】:

    猜你喜欢
    • 2018-02-19
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多