How does the async/await syntax work in TypeScript?

The key is to use an ES6 Promise or something that implements the PromiseLike and PromiseConstructorLike interfaces found in lib.d.ts (Read more). A jQuery promise does not implement these interfaces so it won’t work with that.

Here’s a simple example using an ES6 promise:

function getStringFromWebServerAsync(url: string) {
    return new Promise<string>((resolve, reject) => {
        // note: could be written `$.get(url).done(resolve).fail(reject);`,
        //       but I expanded it out for clarity
        $.get(url).done((data) => {
            resolve(data);
        }).fail((err) => {
            reject(err);
        });
    });
}

async function asyncExample() { 
    try {
        const data = await getStringFromWebServerAsync("http://localhost/GetAString");
        console.log(data);
    }
    catch (err) {
        console.log(err);
    }
}

asyncExample();

Note that any code containing an await statement needs to be within an async function and so I have wrapped the code in one. That said, an upcoming proposal adds “top-level await”, which will be available in TypeScript 3.8. Read more here and see here for TypeScript details.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)