Skip to content

Commit

Permalink
added sendRequestAsync which returns a promise when sending requests
Browse files Browse the repository at this point in the history
  • Loading branch information
liamcottle committed Mar 15, 2021
1 parent 7f4e406 commit 6ea16eb
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
35 changes: 35 additions & 0 deletions examples/6_async_requests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const RustPlus = require('@liamcottle/rustplus.js');
var rustplus = new RustPlus('ip', 'port', 'playerId', 'playerToken');

// wait until connected before sending commands
rustplus.on('connected', () => {

/**
* sendRequestAsync will return a promise for your request.
* you can optionally pass in a second parameter for the timeout in milliseconds
* - AppResponse packets will be sent to `then` on success.
* - AppError packets and Timeout Errors will be sent to `catch`.
*/
rustplus.sendRequestAsync({
getInfo: {}, // get server info with a timeout of 2 seconds
}, 2000).then((response) => {

// AppResponse
console.log(response);

}).catch((error) => {

// AppError or Error('Timeout');
console.log(error);

}).finally(() => {

// disconnect so our script is finished
rustplus.disconnect();

});

});

// connect to rust server
rustplus.connect();
36 changes: 36 additions & 0 deletions rustplus.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,42 @@ class RustPlus extends EventEmitter {

}

/**
* Send a Request to the Rust Server and return a Promise
* @param data this should contain valid data for the AppRequest packet defined in the rustplus.proto schema file
* @param timeoutMilliseconds milliseconds before the promise will be rejected. Defaults to 10 seconds.
*/
sendRequestAsync(data, timeoutMilliseconds = 10000) {
return new Promise((resolve, reject) => {

// reject promise after timeout
var timeout = setTimeout(() => {
reject(new Error('Timeout reached while waiting for response'));
}, timeoutMilliseconds);

// send request
this.sendRequest(data, (message) => {

// cancel timeout
clearTimeout(timeout);

if(message.response.error){

// reject promise if server returns an AppError for this request
reject(message.response.error);

} else {

// request was successful, resolve with message.response
resolve(message.response);

}

});

});
}

/**
* Send a Request to the Rust Server to set the Entity Value.
* @param entityId the entity id to set the value for
Expand Down

0 comments on commit 6ea16eb

Please sign in to comment.