1

I'm dealing with a code that makes calls to an async function. In this case, the run method performs an await call to a method that returns a string. How can I transform the run method to return, again, a promise?

I searched the Internet, but I cannot find a solution. I'm new to Typescript and asynchronous programming.

I'd also like to ask: Does the await keyword "transform" a returned promise in a string? The result is a string, but why do I not have to unwrap it with .then() to obtain the string? If the result was a promise, I could return it in the run method, but run must return a promise.

public async run(): Promise<IMyType> {
    log.info("Running item1 ...");

    let result: IMyType = {
        name: "name1",
        outcome: undefined,
        message: "",
        various: {}
    };

    result = await this.runCheck(result);
    if (result.outcome) {
        result.message = this.successMessage;
    } else {
        result.message = this.failMessage;
    }

    return result;
}


private async runCheck(
    result: IMyType
): Promise<IMyTypet>
SparkFountain
  • 2,110
  • 15
  • 35
user1
  • 556
  • 2
  • 6
  • 22
  • Related: https://stackoverflow.com/q/35302431/457268 – k0pernikus Aug 30 '19 at 08:52
  • 4
    async / await is syntactic sugar to help to work with promises in a seemingly synchronous way (meaning: the code looks like is synchronous, though it still is promise-based). An async function will *always* return a promise. – k0pernikus Aug 30 '19 at 08:56

2 Answers2

1

You already have your answer in your code. When you mark a function with async, it means that it will return a promise, no matter what's inside the function. If you return a value, it will be the value that the promise has resolved with.

The runCheck() is marked with async and you are await-ing it to get the string value. The same goes for the run() function. You have marked it with async which means it will return a promise, no matter what's inside. You are returning the string value, which means you can just do this:

const theString = await object.run(); // theString is the value you return in function
0

Here is how you can return a promise in an async function:

let getSomeValue = async () : Promise<string> => {
    let promise: Promise<number> = new Promise((resolve, reject) => {
        setTimeout(function() { resolve("my result") }, 50); //for example
    });
    return promise;
}

Then you can consume it like this:

let result = await getSomeValue();

and your question:

"does the await keyword "transform" a returned promise in a string?"

Yes, "my result" will be assigned to result here.

Przemek Struciński
  • 4,990
  • 1
  • 28
  • 20