How to return an Ajax result using async/await?

后端 未结 2 1497
面向向阳花
面向向阳花 2020-11-28 11:40

Trying to get familiar with async/await, I\'ve tried the following code in Chrome:

async function f() { 
     return await $.get(\'/\');
};
va         


        
相关标签:
2条回答
  • 2020-11-28 12:03

    await and async are basically just syntactical sugar on top of Promise. If you end up with a Promise at the end, you still need to treat it like a Promise.

    const response = f().then(() => { });
    

    Or, if you are calling it inside of an async function, you can await to resolve it:

    async function main() {
      const response = await f();
      console.log(response);
    }
    

    A pattern I like to use is have my main code wrapped in a self-executing async function, so I can still use await:

    (async () => {
      const result = await doSomething();
      console.log(result);
    })();
    

    Note that even with that pattern, I need a final catch() to catch any errors it may have that aren't caught otherwise:

    (async () => {
      // blah blah
    })().catch(() => {});
    
    0 讨论(0)
  • 2020-11-28 12:23

    either

    function f() { 
      return $.get('/');
    };
    
    async test() {
      var x = await f()
      console.log(x)
    }
    
    test()
    

    or

    f().then(function(res) {
        console.log(res)
    }
    

    the async/await is just another way to write the same logic.

    0 讨论(0)
提交回复
热议问题