Skip to content

Instantly share code, notes, and snippets.

@xavierlepretre
Last active September 7, 2017 16:42
Show Gist options
  • Save xavierlepretre/afab5a6ca65e0c52eaf902b50b807401 to your computer and use it in GitHub Desktop.
Save xavierlepretre/afab5a6ca65e0c52eaf902b50b807401 to your computer and use it in GitHub Desktop.
Get a Promise on events fired
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;
});
};
@xavierlepretre
Copy link
Author

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