Wrapping TE Async Object with a JavaScript Promise
This sample demonstrates how to wrap TE Async Objects with JavaScript promises for easier asynchronous handling. It provides a utility function, TeAsyncObjectPromisify, to perform this wrapping and then showcases two different ways of using it: promises and async/await.
let utils = {
TeAsyncObjectPromisify: function(TeAsyncObject) {
return new Promise((resolve, reject) => {
TeAsyncObject
.OnResolve(result => resolve(result))
.OnReject(error => reject(error))
});
}
}
//connect -> load fly layer into a group -> change group's name
async function AsyncActionsExample() {
var URL = "https://cloud.skylineglobe.com/sg";
var Username = "******";
var Password = "******";
//ITerraExplorerAsync without promisify (nested code)
SGWorld.SGServer.ConnectAsync(URL, Username, Password)
.OnResolve(_ => {
SGWorld.ProjectTree.LoadFlyLayerAsync("https://cloud.skylineglobe.com/SG/demos/projects/TED_Default_Demo_Project_v7")
.OnResolve(groupID =>SGWorld.ProjectTree.RenameGroup(groupID, "New Group Name"))
.OnReject(error => alert(error.message))
})
.OnReject(error => alert(error.message))
//Promisified (flat code)
utils.TeAsyncObjectPromisify(SGWorld.SGServer.ConnectAsync(URL, Username, Password))
.then(_ =>utils.TeAsyncObjectPromisify(SGWorld.ProjectTree.LoadFlyLayerAsync("https://cloud.skylineglobe.com/SG/demos/projects/TED_Default_Demo_Project_v7")) )
.then(groupID => SGWorld.ProjectTree.RenameGroup(groupID, "New Group Name"))
.catch(error => alert(error.message));
//Promisified Async Await (flat code best practice)
try{
await utils.TeAsyncObjectPromisify(SGWorld.SGServer.ConnectAsync(URL, Username, Password));
var groupID = awaitutils.TeAsyncObjectPromisify(SGWorld.ProjectTree.LoadFlyLayerAsync("https://cloud.skylineglobe.com/SG/demos/projects/TED_Default_Demo_Project_v7"));
SGWorld.ProjectTree.RenameGroup(groupID, "New Group Name");
}
catch(e){ alert(error.message); }
}