Using Asynchronous Function when Voting using Steem.js
This tutorial is for solving few issues encountered while using Steem.js.
While working on a simple Discord Upvote Bot I found out that I am getting a lot of Promise Rejection error as well as WebSocket Error and my bot is crashing every time
For Example :
UnhandledPromiseRejectionWarning: Unhandled promise rejection(rejection id: 1): Error:Bad Request
[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,
promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
And
Unhandled rejection Error: not opened
at WebSocket.send (/app/node_modules/ws/lib/WebSocket.js:344:18)
at /app/node_modules/steem/lib/api/transports/ws.js:135:19
at tryCatcher (/app/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/app/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/app/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromiseCtx (/app/node_modules/bluebird/js/release/promise.js:606:10)
So, to fix the first error UnhandledPromiseRejectionWarning, which means is caused by the failed assertion. Since we do not have any control on the inner workings of Steem. The best thing for this is to catch the exception as a promise. So to do that you need to use the Asynchrnous function of the vote i.e. steem.broadcast.voteAsync()
and then use the catch function to catch any error as shown below
steem.broadcast.voteAsync(
process.env.STEEMKEY,
process.env.STEEMAUTHOR,
author,
permalink,
weightPercentage,
function(err, result) {
// Inner Workings
}).catch(function() {
//Error Catching
});
After doing this, I does not see any UnhandledPromiseRejectionWarning.
For Unhandled rejection Error: not opened error we need to add the URL of the steem api by using setOptions, because Steem npm package uses web socket and instead we need to use the Steemit API.
steem.api.setOptions({url: 'https://api.steemit.com'});
These are few of the errors encountered and now the Discord Upvote Bot is ready to be used in all the servers.
Posted on Utopian.io - Rewarding Open Source Contributors