To properly implement getReservedEntityId()
, it is crucial to understand how promises work. I recommend thoroughly reading through the documentation on promises. When dealing with asynchronous tasks in your function, you must ensure that a promise is returned which will either resolve or reject based on the outcome of the asynchronous operation.
function getReservedEntityId(collectionName) {
if (haveCachedIds) {
return Promise.resolve(cachedId);
} else {
return new Promise((resolve, reject) => {
// Perform AJAX call and use resolve(newId) in success callback
// or reject(errCode) in failure callback.
// The `newId` and `errCode` can be any values and are passed
// to the next chain link in the promise like then() or catch()
});
}
}
After ensuring this aspect is taken care of, there are two recommended methods to handle synchronous calls:
1) Using a promise chain
getReservedEntityId(collectionName)
.then((id) => {
// Process `id` first...
return getReservedEntityId(collectionName);
})
.then( ... )
.then( ... );
If you plan to pass the same function to each `.then()` call, consider declaring it as a regular function to avoid redundancy.
2) Employing async/await
This ES2017 feature is not widely supported yet. While Node.js supports async/await with the `--harmony` flag, most browsers do not. Despite this, async/await streamlines handling functions returning promises as if they were synchronous. To incorporate async/await now, transpile your JavaScript using tools that make it compatible with all major browsers.
Here's an example of utilizing async/await:
(async function someAsyncFunction {
const id1 = await getReservedEntityId(collectionName);
const id2 = await getReservedEntityId(collectionName);
const id3 = await getReservedEntityId(collectionName);
.
.
.
})();
The syntax of async/await enhances readability compared to promise chains as it caters to such scenarios. Note that I've implemented a self-invoking function here to align with your approach without needing an additional function call. You can use and invoke a function defined with `async function` similar to any other promise-returning function.