【问题标题】:Unexpected variables in arguments[] when passing a function传递函数时参数 [] 中的意外变量
【发布时间】:2017-02-17 06:22:02
【问题描述】:

我在一个文件夹中有两个文件 - 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 对象中。事实上,arguments 对象保持不变,4 个输入描述了 node_modules 中的一些函数和文件,包括 Bluebird 和对 index.js 本身的引用


我的最终目标是

  1. 将函数从index.js 传递给util.js

  2. 传递未知数量的变量

  3. 调用传递的函数并对其应用未知数量的变量

  4. 将整个事情包装在一个承诺中并进行一些数据验证

理想情况下,arguments[0] 代表我将传递的一个函数,另一个是值。然后我会使用

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

如果有帮助,我要传递的函数有一个可选的回调功能

【问题讨论】:

  • 胖箭头没有自己的 thisarguments 对象。如果你想要这些,你将不得不使用“常规函数”。或者你使用rest parameterobj.sendTransaction = (fn, ...args) => { console.log(fn, args) }
  • 请停止垃圾标签,这个问题与nodejs,prototype或prototypejs无关

标签: javascript node.js prototype apply


【解决方案1】:

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

您可以使用“常规函数”,或者在这种情况下,您可以使用...rest parameter

并且,避免使用 Deferred 反模式。

//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));
    }   
}

【讨论】:

  • 谢谢,我把它改成常规函数并使用了apply。刚刚完成所有测试,但前几个测试通过了。根据这个 bluebirdjs.com/docs/anti-patterns.html ,延迟反模式是使用 superfluous wrapping 而不是简单地返回初始 Promise 本身。我对 Promises 有点陌生,所以不确定为什么我的代码是反模式。如果可以请指出,谢谢
  • @VarunAgarwal 因为冗长且 imo 不必要的 new Promise() 包装器,而每个 resolvedPromise.then() 都可以完成这项工作;甚至处理拒绝部分。但这只是一个小问题。
猜你喜欢
  • 2012-04-12
  • 2020-10-21
  • 1970-01-01
  • 2017-12-18
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多