AsyncTask

API Reference: AsyncTask

AsyncTask can be used in cases where UI thread can cause performance issues. AsyncTask creates a different thread to overcome this.

Use Cases

  • Downloading large files

  • Accessing DB

  • Parsing JSON

  • And other heavy operations such as searching in large text

AsyncTask is used for non UI operations. Any UI operation performed in task method will result in unexpected errors.

In the following example, assume we have performed a request that will response with large data. That large data is parsed using AsyncTask.

JavaScript
JavaScript
const AsyncTask = require("sf-core/asynctask");
const extend = require('js-base/core/extend');
const Page = require('sf-core/ui/page');
const Http = require("sf-core/net/http");
var http = new Http();
var page1 = extend(Page)(
function(_super, params) {
_super(this, params);
this.onLoad = function() {
http.request({
"url": "https://api.github.com/repos/smartface/contxjs",
"method": "GET",
onLoad: function(response) {
var result = response.body.toString();
var parsedObject;
// Run new task
var asyncTask = new AsyncTask();
asyncTask.task = function() {
parsedObject = JSON.parse(result);
};
asyncTask.onComplete = function() {
// Do something with parsedObject
};
asyncTask.run();
},
onError: function(e) {
// Handle error
}
});
};
}
);
module.exports = page1;