Skip to content

Instantly share code, notes, and snippets.

@xavierlepretre
Created January 8, 2017 17:36
Show Gist options
  • Save xavierlepretre/90f0feafccc07b267e44a87050b95caa to your computer and use it in GitHub Desktop.
Save xavierlepretre/90f0feafccc07b267e44a87050b95caa to your computer and use it in GitHub Desktop.
Convert `web3` asynchronous calls into Promises.
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);
});
};
}
});
});
},
};
@JohnAllen
Copy link

JohnAllen commented Sep 29, 2017

@renexdev You have to import PromisifyWeb3 like @xavierlepretre mentioned in the post above yours:

const PromisifyWeb3 = require("./promisifyWeb3.js");
PromisifyWeb3.promisify(web3);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment