2017-02-17 62 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