Created
January 8, 2017 17:36
-
-
Save xavierlepretre/90f0feafccc07b267e44a87050b95caa to your computer and use it in GitHub Desktop.
Convert `web3` asynchronous calls into Promises.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
promisify: function (web3) { | |
// Pipes values from a Web3 callback. | |
var callbackToResolve = function (resolve, reject) { | |
return function (error, value) { | |
if (error) { | |
reject(error); | |
} else { | |
resolve(value); | |
} | |
}; | |
}; | |
// List synchronous functions masquerading as values. | |
var syncGetters = { | |
db: [], | |
eth: [ "accounts", "blockNumber", "coinbase", "gasPrice", "hashrate", | |
"mining", "protocolVersion", "syncing" ], | |
net: [ "listening", "peerCount" ], | |
personal: [ "listAccounts" ], | |
shh: [], | |
version: [ "ethereum", "network", "node", "whisper" ] | |
}; | |
Object.keys(syncGetters).forEach(function(group) { | |
Object.keys(web3[group]).forEach(function (method) { | |
if (syncGetters[group].indexOf(method) > -1) { | |
// Skip | |
} else if (typeof web3[group][method] === "function") { | |
web3[group][method + "Promise"] = function () { | |
var args = arguments; | |
return new Promise(function (resolve, reject) { | |
args[args.length] = callbackToResolve(resolve, reject); | |
args.length++; | |
web3[group][method].apply(web3[group], args); | |
}); | |
}; | |
} | |
}); | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@renexdev You have to import
PromisifyWeb3
like @xavierlepretre mentioned in the post above yours: