简体   繁体   中英

Typescript, promises, and async await confusion

I'm writing code in Typescript and I'm having trouble with libraries which lack synchronic functions/methods. I just need to wait for a promise to be resolved and I can't find a reasonable way of doing so. What I intend to do is just:

public someObjectMethod(): any {
    externalLibrary.doSomeghing()
    // wait for that something to happen
    // continue doing stuff

I know I can make the method async so it returns a Promise and then declare the calling method async too so that it also returns a Promise and so on until I eventually get to a point where I can await , but if I do that I'll end up with an object model where every method is async and every object is a Promise . The thing is that I took Typescript for this expecting to be able to write OO code and not a Javascript script. I don't think using Promises , async and await will scale in a big OO model and I really don't need the extra performance I can get from asynchronous calls but rather the flow control I can get from synchronous calls.

So the question is... Is there a - reasonable - way to wait for Promises to resolve?

THIS IS NOT A DUPLICATE QUESTION!

I'm asking if there's a reasonable way of waiting for a Promise to resolve in the context of writing an object-oriented model. Changing all functions in the call trace to async and then handling Promises everywhere is not a reasonable way of solving this problem. I need to know if there's a way of just waiting for a Promise to resolve instead of changing the signature of half my code every time I come across a library which doesn't have synchronous implementations.

Once you're invoking async code - whether it uses "callback hell", Promises, async/await (syntactic sugar around Promises), or even something Monadic (is that a dirty word?) - I'm afraid you're stuck in async code.

You can convert between callback syntax and Promises, if you like.

function foo(cb: (err: any, value: string) => void): void {
   doSomethingPromisey()
       .then(
           (value) => cb(null, value),
           cb
       );
}

foo((err: any, value: string) => {
    if (err) {
        // Do something with the error here.
        // Note that throwing an error will just cause a Promise rejection - once you're in a Promise chain, there's no escaping!
        throw new Error("It didn't work :(");
    } else {
        console.log(value);
    }
});

But this isn't want you want.

I see your options as:

  • Fork the libraries to write synchronous versions of the code.
  • Accept Promises into your life & codebase.

Based on my experience, you have nothing to fear using promises in OO code. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM