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>
2
  • Related: stackoverflow.com/q/35302431/457268 Commented Aug 30, 2019 at 8: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. Commented Aug 30, 2019 at 8:56

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.