You cannot make a synchronous result out of an asynchronous operation in Javascript. You just cannot do it. If any part of your operation is async, the entire result must be async and you must either use a callback, a promise or some other such mechanism to communicate when the operation is done and the result is ready.
If your async operation already returns a promise (which it looks like), then you should just return that from the wrapper function:
function myWrapperFunction() {
var accumulator = {};
var myPromise = doAsynchronousThingThatSideEffectsAccumulator(accumulator);
// Now my caller is expecting the value of accumulator.
return myPromise.then(function(result) {
// operate on the accumulator object using the async result
return accumulator;
})
}
myWrapperFunction.then(function(accumulator) {
// write your code here that uses the accumulator result
});
You may also want to note that a function that operates via side effects is rarely the best design pattern. You may as well pass in the input and have it return the output via the resolved promise and avoid side effects entirely.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…