Last active
September 7, 2017 16:42
-
-
Save xavierlepretre/afab5a6ca65e0c52eaf902b50b807401 to your computer and use it in GitHub Desktop.
Get a Promise on events fired
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
getEventsPromise= function (myFilter, count, timeOut) { | |
timeOut = timeOut ? timeOut : 30000; | |
var promise = new Promise(function (resolve, reject) { | |
count = (typeof count !== "undefined") ? count : 1; | |
var results = []; | |
var toClear = setTimeout(function () { | |
reject("Timed out"); | |
}, timeOut); | |
myFilter.watch(function (error, result) { | |
if (error) { | |
clearTimeout(toClear); | |
reject(error); | |
} else { | |
count--; | |
results.push(result); | |
} | |
if (count <= 0) { | |
resolve(results.map(value => value)); | |
clearTimeout(toClear); | |
myFilter.stopWatching(() => {}); | |
} | |
}); | |
if (count == 0) { | |
promise = promise | |
.then(function (events) { | |
throw "Expected to have no event"; | |
}) | |
.catch(function (error) { | |
if (error != "Timed out") { | |
throw error; | |
} | |
}); | |
} | |
return promise; | |
}); | |
}; |
If you want to make sure there is no event at a given block:
getEventsPromise(myContract.LogRequest({}, { fromBlock: blockNumber, toBlock: blockNumber }), 0, 1000)
.then(function () {
console.log("No event, as expected");
})
.catch(function(error) {
console.error(error);
console.error("There were events or another error");
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of use: