0

Is there any way a non async function can return the resolved Promise value? Or for async to return non Promise?

I have a module A that I want to import dynamically in module B. Since it's dynamical it produces a promise. From module B I would like to expose part of it (the resolved part of adapterPromise) as a non Promise object.

const foo = async () => {
  return await adapterPromise;
};

export const MyAdapter = () => foo(); // I don't want this to be a Promise

The problem I run into is that since foo is async, then it always produces a Promise and I'd like to avoid that (the reason is that MyAdapter consists of functions that I want to call repeatedly and as far as I know, the same Promise shouldn't be resolved multiple times).

It is possible to do this with Top level await

export default await adapterPromise;

I'm curious if this is the only way.

user1335014
  • 351
  • 1
  • 4
  • 13
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – tevemadar Oct 13 '22 at 14:04
  • Why not call those functions in `MyAdapter` after the promise resolves? – Ivar Oct 13 '22 at 14:04
  • @tevemadar I think your link talked more generally about how to use Promises, but didn't really address how I wanted to use it. – user1335014 Oct 19 '22 at 18:13
  • @Ivar I believe that requires additional safe guarding against too early calls which makes it more complex. However, I can't see a better way to it might be the best way forward. – user1335014 Oct 19 '22 at 18:24

1 Answers1

0

There is no way to return the Promise value. But you can definitely use it in a callback function

function foo (callback) {
  var p = ...; // a promise
  p.then(function(a) {
    callback(a);
  });
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • My scenario is to return object which whose methods will be called multiple times, so I don't think this approach is applicable (I don't have a single callback to call once promise is resolved). – user1335014 Oct 19 '22 at 18:26
  • @user1335014 just combine your callbacks into a single function. This is the only other way besides using await – ControlAltDel Oct 19 '22 at 18:31
  • It still wouldn't work, the functions are being called elsewhere at various times, some behind user interactions (so there is no way to define a single callback). There is a service behind this adapter, my goal was to initialize this service and make it available at all times. – user1335014 Oct 21 '22 at 00:07