Suitescript 2.1 features – Promise and Async-Await with sample

The latest version of SuiteScript includes enhancements in SuiteScript 2.1, such as improved asynchronous processing and new APIs for better integration. Developers can leverage these features to create more efficient and responsive scripts.

Promise Support

Promises in JavaScript represent the eventual completion (or failure) of an asynchronous operation and its resulting value. SuiteScript 2.1 introduces promise-based APIs for several modules, including N/http, N/https, N/query, N/search, and N/transaction1. This means that developers can now write non-blocking code that is more efficient and easier to manage.

// Using promises in SuiteScript 2.1
const https = require('N/https');


function fetchData() {
    let promise1 = https.get.promise({ url: 'https://example.com/api/data1' });
    let promise2 = https.get.promise({ url: 'https://example.com/api/data2' });


    Promise.all([promise1, promise2])
        .then(results => {
            console.log('Data1:', results[0].body);
            console.log('Data2:', results[1].body);
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

In this example, two HTTP GET requests are made concurrently. The Promise.all method ensures that both promises are resolved before proceeding, significantly reducing the total execution time compared to synchronous code.

Async-Await Syntax

The async-await syntax, introduced in ECMAScript 2017, allows developers to write asynchronous code that looks and behaves like synchronous code. This makes the code more readable and easier to debug. SuiteScript 2.1 fully supports async-await for the same set of modules that support promises

// Using async-await in SuiteScript 2.1
const https = require('N/https');


async function fetchData() {
    try {
        let response1 = await https.get.promise({ url: 'https://example.com/api/data1' });
        let response2 = await https.get.promise({ url: 'https://example.com/api/data2' });


        console.log('Data1:', response1.body);
        console.log('Data2:', response2.body);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

In this example, the await keyword pauses the execution of the fetchData function until the promise is resolved, making the code flow more naturally.

Benefits of Asynchronous Programming

Improved Performance: By allowing multiple operations to run concurrently, asynchronous programming can significantly reduce the total execution time of scripts1.

Better Resource Utilization: Non-blocking code ensures that the server can handle more requests simultaneously, improving overall system efficiency.

Enhanced User Experience: Faster execution times lead to quicker responses, providing a better experience for end-users.

Leave a comment

Your email address will not be published. Required fields are marked *