Promises in SuiteScript 2.x for Asynchronous Programming
SuiteScript 2.x promise APIs enable efficient asynchronous programming, improving code structure and error handling.
A promise is a JavaScript object representing the eventual result of an asynchronous process. After a promise is created, it acts as a placeholder for the future success or failure of the async operation, allowing other script segments to execute meanwhile. This enables developers to write clearer, more efficient asynchronous code.
What Are Promise States?
A promise can hold one of the following states:
fulfilled: The operation completed successfully.rejected: The operation failed.pending: The operation is still in progress and has not completed yet.
Initially, a promise is pending. Once the associated process completes, it will either change to fulfilled on success or rejected on failure. It’s important to note that a promise can only resolve or reject once; once the state is set, it cannot be changed again.
SuiteScript Promise APIs
SuiteScript 2.x provides promise APIs for various modules. All client scripts support the use of promises, and as of NetSuite 2021.1, a subset of server scripts can also utilize them. You can create custom promises in client scripts. Here’s a list of supported modules and some example implementations:
Example: Basic Promise Usage
In this example, we demonstrate a basic usage of the search.create.promise method within a client script's pageInit entry point:
1/**2* @NApiVersion 2.x3*/4 5define(['N/search'], function(search) {6 function doSomething() {7 search.create.promise({8 type: 'salesorder'9 })10 .then(function(result) {11 log.debug("Completed: " + result);12 // Handle success13 })14 .catch(function(reason) {15 log.debug("Failed: " + reason);16 // Handle failure17 });18 }19 return {20 pageInit: doSomething21 };22});Example: Chaining Promises
You can chain promises together for more complex operations. Here's an example where we use a filter and chain a search object:
1/**2* @NApiVersion 2.x3*/4 5define(['N/search'], function(search) {6 function doSomething() {7 var filter = search.createFilter({8 name: 'mainline', 9 operator: search.Operator.IS, 10 values:['T']11 });12 13 search.create.promise({14 type: 'salesorder', 15 filters:[filter]16 })17 .then(function(searchObj) {18 return searchObj.run().each.promise(function(result, index) {19 // Do something with each result20 });21 })22 .then(function(result) {23 log.debug("Completed: " + result);24 // Final success action25 })26 .catch(function(reason) {27 log.debug("Failed: " + reason);28 // Handle failure29 });30 }31 return {32 pageInit: doSomething33 };34});Custom Promises
The following example shows how to create a custom promise without using SuiteScript’s promise APIs:
1/**2* @NApiVersion 2.x3*/4 5define(function() {6 function doSomething(addresses) {7 var promise = new Promise(function(resolve, reject) {8 var url = 'https://your.favorite.maps/api/directions?start=' + addresses.start + '&end=' + addresses.end,9 isAsync = true,10 xhr = new XMLHttpRequest();11 12 xhr.addEventListener('load', function(event) {13 if (xhr.readyState === 4) {14 if (xhr.status === 200) {15 resolve(xhr.responseText);16 } else {17 reject(xhr.statusText);18 }19 }20 });21 22 xhr.addEventListener('error', function(event) {23 reject(xhr.statusText);24 });25 26 xhr.open('GET', url, isAsync);27 xhr.send();28 });29 30 return promise;31 }32 33 return {34 lookupDirections: doSomething35 };36});Key Considerations
When coding with promises in SuiteScript:
- Always utilize
.catch()for rejection handling. - Avoid nesting promises; prefer chaining them.
- Keep promise chains short to ensure performance.
- Use
Promise.all()for handling multiple asynchronous calls concurrently. - When using
async/await, note that these keywords work only with certain supported modules.
Key Takeaways
- Promises allow for more manageability in asynchronous code execution.
- SuiteScript 2.x has integrated promise APIs for smooth operations.
- Best practices for using promises can enhance performance and readability in scripts.
Frequently Asked Questions (4)
Are promises available in all NetSuite scripts?
Can I use async/await with promises in SuiteScript 2.x?
What is the best way to handle promise rejection in SuiteScript?
How can I execute multiple asynchronous operations concurrently in SuiteScript 2.x?
Was this article helpful?
More in SuiteScript
- Common SuiteScript Errors and Solutions for NetSuite
Common NetSuite script errors include INVALID_SCRIPT_DEPLOYMENT_ID and SSS_AUTHORIZATION_HEADER_NOT_ALLOWED. Learn effective solutions.
- Set Sublist Field Values in SuiteScript 2.x for Record Management
Set sublist field values in SuiteScript 2.x for effective record management using standard and dynamic modes.
- Setting Field Values in SuiteScript for Effective Record
Learn to set field values in SuiteScript effectively, troubleshooting common errors and understanding data types.
- SuiteScript 2.1 Enhancements and API Updates in NetSuite
SuiteScript 2.1 enables execution of 2.0 scripts and supports PATCH method for enhanced API capabilities.
Advertising
Reach SuiteScript Professionals
Put your product in front of NetSuite experts who work with SuiteScript every day.
Sponsor This Category