When using promises in your SuiteScript scripts to implement asynchronous programming, you should consider the following best practices.
If you are using SuiteScript 2.1 scripts, consider using the async and await keywords to implement asynchronous solutions instead of using the promise keyword.
Best practices for coding promises:
- Always use a promise rejection by including a promise.catch handler.
- Do not nest promises. Chain your promises instead. Or use
async/awaitfunctionality. - Keep promise chains short to avoid significant overuse of memory and CPU.
- Use
promise.finallyif you have code that should run regardless of the outcome of the promise. - Use
promise.allfor multiple unrelated asynchronous calls. - Do not define rejection handlers as the second argument for
promise.thencalls. Instead, usepromise.catch. - If you need to access results of promises running in parallel, use
promise.spread. - To limit concurrency, use
promise.map. - Use
promise.thento run code after the promise completes.
Best practices when using async and await keywords:
- Rewrite promise code to use
async/await. - Schedule first, await later.
- Avoid mixing callback-based APIs with promise-based APIs.
- Refrain from using
returnawait. - Remember that for SuiteScript 2.1 server-side scripts, only a subset of modules support the use of the
asyncandawaitkeywords: N/http, N/https, N/llm, N/query, N/search, and N/transaction.