My script requires me to make an XML request, receive the response from the server (if resolved), parse it, and store the parsed result in a variable.
Only after this process can I proceed with various tasks.
To achieve this separation of concerns, I aim to:
- Encapsulate the above process into a function in an external script that can be called when necessary.
- Avoid having all my code within a
.then()
method. - Organize my code into logical files, each dedicated to a specific task.
I have come up with a sample piece of code to illustrate my requirements. However, as I am relatively new to asynchronous programming, I wonder if it is acceptable to structure my code in this manner, considering that the response should be resolved quickly in my scenario.
If this approach is suitable, I plan to place this code snippet in a separate file for easy importing and calling of the function testing()
(or whatever its name may be) from any part of my project.
function delay(input) {
return new Promise(function(resolve, reject) {
// perform some async operation here
setTimeout(function() {
// resolve the promise with a value
resolve(input + 10);
}, 500);
});
}
function testing() {delay(5).then(result => {return document.write(result)})};
testing();
EDIT
Upon reviewing the insights provided by @DrewReese and the references in the comments, I believe I have identified the issue at hand.
The above code example was slightly misleading in conveying my intention, but I recognize that there might not be a straightforward solution. Consider the following code snippet (essentially similar to the previous one, except for the last three lines):
function delay(input) {
return new Promise(function(resolve, reject) {
// perform some async operation here
setTimeout(function() {
// resolve the promise with a value
resolve(input + 10);
}, 500);
});
}
function testing() {delay(5).then(result => {return result})};
var test = testing();
document.write(test);
In this scenario, I understand that defining test
results in 'undefined'
since the Promise within testing()
is yet to be resolved.
The challenge I face is: Is it possible to assign a value to test
only once the Promise is resolved, without necessitating a then()
, and potentially display a different output while waiting for resolution (such as "LOADING...")?
I am unsure if it is feasible to determine whether a variable holds a pending Promise and showcase two distinct values based on its state: awaiting resolution or already fullfiled/rejected.
I trust that my explanation is clear; otherwise, I will explore further and pose another question if required.