A
A
Al2017-03-07 23:43:44
JavaScript
Al, 2017-03-07 23:43:44

Why doesn't async/await work?

I use typescript ("lib": ["dom", "es2015.promise", "es5"])
Example:

function exec(url) {
    return new Promise(resolve => {
        let responce = null;
        $.ajax({
            type: 'GET',
            url: url
        }).done((data) => {
            resolve(data);
        });
    });
}

async function request(url) {
    return await exec(url);
}

let data = request('/ru/catalog');
console.log(data);

this example returns:
: "pending"
: "["undefined"]"

All due to the fact that the resolve does not reach, but the promise is returned. How to make it wait to return data (data) instead of a promise?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly, 2017-03-08
@Sanu0074

In order not to grow callback hell, use a construction inside which there will be all async code.

async function  request(url) {(
        try {
            await function(){
                $.ajax({
                    type: 'GET',
                    url: url,
                    success: (data) =>{
                        return data;
                    }
                })
            };
        } catch (error) {
            console.error(error);
            throw error;
        }
}

(async ()=>{
   try {
      await ....
      // весь асинк код
      let data = await request('/ru/catalog');
      console.log(data);
       return 1;
} catch (error) {
      console.error(error);
      throw error;
   }
})();

Return and frow are required, because in fact you describe a promise and after () you can continue to vermicelli then catch and so on

S
Stepanya, 2017-03-08
@Stepanya

let data = await request('/ru/catalog');

let data = request('/ru/catalog').then((data) => console.log(data));

N
netW0rm, 2017-03-08
@netW0rm

await only works inside a function declared as async.
I usually do this

main()
async function main() {
  ...
  let data = await request('/ru/catalog')
  ...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question