0

I don't get return value async/await function.

I give real code following:

class TranslateAlert{
......
    public async translateEn2Ja(englishText: string): Promise<string | Error> {
        englishText = englishText.replace(/(<([^>]+)>)/ig, " ").replace(/\r?\n/g, " ").replace("  ", " ").trim();

        const translatedText = await this.translateAPI.post(
            TranslateAPIURL, [{ "text": englishText }]
        ).catch((error) => { throw new Error(error) });

        if (translatedText) {
            return translatedText.data[0].translations[0].text;
        }
    }
}

Above code is used from follwoing code:

   public createMessage(): string {
        const t = new TranslateAlert();
        const f = (async () => {
            await t.translateEn2Ja("Test").then((v) => {
                return v;
            })
        })();
        console.log(f);  <-------- this is "Promise { <pending> }"
   }

I would like to get translated text. But I got only "Promise { }".

When I changed to following code, it didn't execute:

        t.translateEn2Ja("Test").then((v) => {
            console.log("=========================");
            console.log(v);
            console.log("=========================");
            return v;
        });

Could you let me know how to get correct data?

tsunomur
  • 25
  • 5
  • 1
    1) Get rid of the `.catch(...)` block, it doesn't do anything useful. 2) That second snippet doesn't help, you need to `await` the `async () => {}` function you're creating as well, which means `createMessage` must also be `async`. You can't turn an async function into a sync function this way. 3) The third approach should work, assuming that `translateAPI.post` ever resolves. What does that mean "it didn't execute"? – deceze Mar 19 '20 at 08:36
  • Thank you @deceze, I changed to async createMessage from no-async createMessage. – tsunomur Mar 19 '20 at 10:00

0 Answers0