Using Async/Await with JSOM

Async/Await can make JSOM coding much easier and is simple to set up. All you need to do is wrap your executeQuery calls in a Promise, then you can await them!


await new Promise((resolve, reject) => {

clientContext.executeQueryAsync((x) => {

resolve();

}, (error) => {

console.log(error);

reject();

});

});

Here’s a full example of a method that hides the firs webpart on the page:


public async AddWebPartToEditForm(webRelativeUrl: string, editformUrl) {

const clientContext: SP.ClientContext = new SP.ClientContext(webRelativeUrl);

var oFile = clientContext.get_web().getFileByServerRelativeUrl(editformUrl);

var limitedWebPartManager = oFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);

let webparts = limitedWebPartManager.get_webParts();

clientContext.load(webparts, 'Include(WebPart)');

clientContext.load(limitedWebPartManager);

await new Promise((resolve, reject) => {

clientContext.executeQueryAsync((x) => {

resolve();

}, (error) => {

console.log(error);

reject();

});

});

let originalWebPartDef = webparts.get_item(0);

let originalWebPart = originalWebPartDef.get_webPart();

originalWebPart.set_hidden(true);

originalWebPartDef.saveWebPartChanges();

await new Promise((resolve, reject) => {

clientContext.executeQueryAsync((x) => {

console.log("the webpart was hidden");

resolve();

}, (error) => {

console.log(error);

reject();

});

});

}

 

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s