2017-02-17 51 views
0

我有一个文件夹中的两个文件 - index.jsutil.js与他们的代码库如下意外变量

util.js中

let obj = {} 
obj.sendTransaction =() => { 
    console.log(arguments); 
    return new Promise((resolve, reject) => { 
    // try { 
    // let data = ethFunction.call() 
    // resolve(data) 
    // } catch (e) { 
    // reject(e) 
    // } 
    }); 
} 
module.exports = obj 

Index.js,如果我通过参数addNewParticipant或其变化那么他们不会在参数调高对象util.js,例如

const addNewParticipant = (foo, bar) => { 
    var ethFunction = myContract.addParticipant.sendTransaction 
    console.log(ethFunction); 
    EthUtil.sendTransaction() 
} 

const addNewParticipantTwo = (foo, bar) => { 
    var ethFunction = myContract.addParticipant.sendTransaction 
    console.log(ethFunction); 
    EthUtil.sendTransaction(ethFunction, foo, bar) 
} 

并将其称为addNewParticpant(1, 2)addNewParticpantNew(1, 2)数字1和2不显示在util函数的参数对象中。事实上,arguments对象保持相同,4个输入描述的一些功能和文件node_modules包括Bluebirdindex.js基准本身


我的最终目的是

  1. 从传递函数index.jsutil.js

  2. 传递未知数量的变量

  3. 调用传递的功能,并在承诺适用未知数量的变量它

  4. 包住整个事情,做一些数据验证

理想arguments[0]将是一个功能我会及格,另一个就是价值。然后我会用

var result = arguments[0].apply(null, Array().slice.call(arguments, 1)); 

如果有帮助,我想通过函数有一个可选的回调特征

+1

胖箭头没有自己的'this'或'arguments'对象。如果你想要这些,你将不得不使用“常规功能”。或者使用[rest参数](// developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/rest_parameters)'obj.sendTransaction =(fn,... args)=> {console.log (fn,args)}' – Thomas

+0

请停止发送垃圾邮件标签,这个问题与nodejs,原型或原型无关 – Thomas

回答

1

正如评论已经提到,脂肪箭没有自己的thisarguments对象。您记录的arguments对象来自模块加载器创建的函数及其传递的参数。

您可以使用“常规功能”,或在这种情况下,你可以使用一个...rest parameter

而且,避免延迟反模式。

//first a little utility that might be handy in different places: 
//casts/converts a value to a promise, 
//unlike Promise.resolve, passed functions are executed 
var promise = function(value){ 
    return typeof value === "function"? 
     this.then(value): 
     Promise.resolve(value); 
}.bind(Promise.resolve()); 

module.exports = { 
    sendTransaction(fn, ...args){ 
     return promise(() => fn.apply(null, args)); 
    } 
} 
+0

谢谢,我将它改为常规函数并使用apply。刚刚结束所有的测试,但前几个通过。根据http://bluebirdjs.com/docs/anti-patterns.html,延迟反模式是在使用“多余的包装”而不是简单地返回初始Promise本身时。我对Promises有点新,所以不确定为什么我的代码是反模式。如果你可以请指出,谢谢 –

+0

@VarunAgarwal,因为每一个'resolvedPromise.then()'都做了这个工作,因为verbose和imo不需要'new Promise()'包装器。甚至处理拒绝部分。但这只是一个小点。 – Thomas