I am trying to optimize an existing javascript
code and finding it hard with callback
methods. This is pure javascript
and no jQuery, Ajax call, or other frameworks involved
.
Here is the issue
function A() {
// getSomeData is a method which takes parameter and a callback
getSomeData(params, function(details) {
// a lot of code in this callback
});
}
The getSomeData
is being used in many places and passing a different callback
at each usage. Trying to optimize and want to use a common method as below but unable to. I like the async/await
approach if possible, else Promise
functionB(keys) {
getSomeData(keys, function(details) {
// move some common code to callback and update some global vars
});
}
functionA() {
// some code block-a
functionB(keys);
console.log(global.x); // this global.x is populated in callback of getSomeData
// some code block-b
}
How ever in the above code, when the functionB
is called and without waiting for callback
to be completed, the console.log(global.x)
is printed as empty/null/undefined
since javascript is async
.
How to achieve this to be synchronous
I tried defining functionB
to be async
as below but did not work
async functionB(keys) {
await getSomeData(keys, function(details) {
// move some common code to callback and update some global vars
});
}
PS: getSomeData(params, callback)
cannot be modified as it is out of control