'Promise on a server-side script (User Event) executing synchronously?
If I understood the Promise behavior correctly, it's used so that anything inside the custom Promise will be executed asynchronously.I did a test user event script and found out that it's executed synchronously.
My sample code below:
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
define(['N/runtime', 'N/https', 'N/url'], function (runtime, https, url) {
function beforeLoad(context) {
try {
log.debug({ title: 'promise 1 start', details: new Date() });
let promise1 = new Promise((resolve) => {
let response = https.requestRestlet({
headers: { 'Content-Type': 'application/json' },
scriptId: 'customscript_test_rl',
deploymentId: 'customdeploy_test_rl',
body: JSON.stringify({ foo: 'bar' })
});
// resolve(response.body);
log.debug({ title: 'response1', details: response });
});
log.debug({ title: 'promise 1 end', details: new Date() });
log.debug({ title: 'promise 2 start', details: new Date() });
let promise2 = new Promise((resolve) => {
let response = https.requestRestlet({
headers: { 'Content-Type': 'application/json' },
scriptId: 'customscript_test_rl',
deploymentId: 'customdeploy_test_rl',
body: JSON.stringify({ foo: 'bar' })
});
// resolve(response.body);
log.debug({ title: 'response2', details: response });
});
log.debug({ title: 'promise 2 end', details: new Date() });
} catch (ex) {
log.debug({ title: ex.name, details: ex });
}
}
return {
beforeLoad: beforeLoad
};
});
Am I doing something wrong or am I wrong about the behavior of a promise?
Solution 1:[1]
Am I wrong about the behavior of a promise?
Yes, you are wrong. The promise executor function is executed synchronously. You don't use a promise to make something that is naturally synchronous into an asynchronous operation. It doesn't do that.
A promise is a notification mechanism for managing and communicating the completion of an operation that is already asynchronous. It doesn't make anything asynchronous that wasn't already asynchronous.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jfriend00 |
