Task object represents a Task - coroutine - function that can be paused at some point and returns a value. When the coroutine is called again, it is resumed right from the point it was paused and its environment remains intact.
In Sciter there ar two types of coroutines:
yield
statement inside.await
statement in its body.To create generator or asynchronous task you define function that uses either yield or await inside:
Asynchronous task:
async function getRemoteData(url) { // Async task try { var data = await self.request(#get, url); return data; } catch (e) { return null; } }
Generator:
function* listItemsBackward(list) { // Generator task for(var i = list.length - 1; i >= 0; --i) yield list[i]; } // use of generator: var list = [0,1,2,3]; for(var item in listItemsBackward(list)) stdout.println(item);
To start Generator or Asynchronous Task you call it as any other function. The only difference from normal functions is that it completes immediately and returns Task object.
The Task object holds the function, its state and represents future value that will be available either on completions of awaited statement (Asynchronous Task) or on invocation of its next() method.
Asycnhronous Task object has method then()
that matches Promise/A+ specification and so it can be treated as a promise. For examlpe, this is another asynchronous task that start two other tasks in parallel and waits for their completion:
function getRemoteDataItems() { // waiting both requests to complete: var items = promise.when( getRemoteData("http://example.com/api/v2/item1" ), getRemoteData("http://example.com/api/v2/item2" )); stdout.println(items[0],items[1]); }
adds onFulfilled and onRejected callback functions to the list of task callbacks. Either onFulfilled(result) and onRejected(error) will be called on task completion.
then() method can be called on asynchronous task coroutine.
adds onRejected callback function to the list of task callbacks. onRejected(error) will be called if task ends with error thrown.
catch() method can be called only on on asynchronous task coroutine.
Equivalent of task.then(null, onRejected);
call.
adds onComplete callback function to the list of task callbacks. onComplete(result | error) will be called on task completion.
then() method can be called on asynchronous task coroutine.
Equivalent of task.then(onComplete, onComplete);
call.
invokes the generator function and returns value reported by yield statement in function.
next() method can be called on generator coroutine only.