-
Notifications
You must be signed in to change notification settings - Fork 7
Functions (Client)
If you want to run the function, and you do not need to control the lifetime of the threads, use BasRemoteClient instance for this. In this case, the client itself creates and terminates BAS threads to perform functions.
The runFunction()
method returns an modified Promise
object.
Using it, you can stop the execution of a running function, get the ID of the thread in which it was run, or get the function result using async/await
or then/catch
.
Take a look at the examples:
const client = new BasRemoteClient({scriptName: 'TestRemoteControl'});
await client.start();
// Run function and get result using 'await'.
const result = await client.runFunction('GoogleSearch', { Query: 'cats' });
console.log(result);
// Run function and get result using 'then'.
const promise = client.runFunction('GoogleSearch', { Query: 'cats' })
.then((links) => console.log(links));
await promise;
// Start functions.
const promise1 = client.runFunction('GoogleSearch', {Query: 'cats'});
const promise2 = client.runFunction('GoogleSearch', {Query: 'dogs'});
// Wait for both functions to finish.
const results = await Promise.all([promise1, promise2])
// Output results.
results.forEach(result => console.log(result))
You can also wrap your function call to try/catch block in order to handle possible errors that may be returned by function. All function errors contains custom error message returned by your script.
try {
await client.runFunction('NotExistingFunction');
} catch(err) {
console.log(err.message);
}
runFunction
returns modified Promise
which contains stop()
method. By calling this method you can immediately stop function execution. It can be useful if you want to add timeouts to call your function or you don't want to wait for it to complete.
In the example below, a function is called that takes a very long time, but we stop it after ten seconds of waiting.
const resultPromise = client.runFunction('LongRunningFunction')
.catch((err) => {
// Handle 'Task stopped manually' error.
console.log(err.message);
});
// Stop function execution after ten seconds.
setTimeout(() => {
resultPromise.stop();
}, 10000);