Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an Ajax result using async/await? [duplicate]

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

async function f() { 
     return await $.get('/');
};
var result = f();

but result doesn't hold the result (string); rather it holds a Promise which needs to be awaited again. This code does give me the response string:

var response = await $.get('/');

How can I return the actual response string from a function using await?

like image 222
user3599803 Avatar asked Jan 29 '18 17:01

user3599803


People also ask

How do I return ajax result?

Hello @kartik, What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, onComplete): somefunction: function(callback){ var result = ""; myAjax = new Ajax.

Can we use async await in ajax?

Since async/await is just Promise's under the hood, I wonder if I can use async/await with jQuery's $. ajax(). Turns out, you can!

Can an async function return a value?

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.


2 Answers

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.

like image 76
messerbill Avatar answered Nov 12 '22 23:11

messerbill


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(() => {});
like image 27
samanime Avatar answered Nov 12 '22 23:11

samanime