How to use async or promise with JQuery $.get? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
How can I return the value from an async function?
I tried to like this
const axios = require('axios');
async function getData() {
const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
}
console.log(getData());
it returns me this,
Promise { <pending> }

You cant await something outside async scope. To get expected result you should wrap your console.log into async IIFE i.e
async function getData() {
return await axios.get('https://jsonplaceholder.typicode.com/posts');
}
(async () => {
console.log(await getData())
})()
Working sample.
More information about async/await
Since axios returns a promise the async/await can be omitted for the getData function like so:
function getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}
and then do same as we did before
(async () => {
console.log(await getData())
})()

your function getData will return a Promise.
So you can either:
await the function as well to get the result. However, to be able to use await, you need to be in an async function, so you need to 'wrap' this:
async function callAsync() {
var x = await getData();
console.log(x);
}
callAsync();
(I named the function for sake of clarity, but in this scenario, one would rather use an anonymous function call; see TheReason's answer.)
or
use the result as a normal Promise, which is what an async function returns.
You have to use then with a callback:
getData().then(x => {
console.log(x);
});

The other answers have covered this fine; but I'd like to chip in and say get in the habit of creating and calling a main function rather than run things in the global scope. i.e.
async function main(){
let result = await getData();
}
main().catch(console.log);
This is pretty clear to anyone reading your code that this is your app entry point

Related

Unable to output number when attempting to find element value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
How can I return the value from an async function?
I tried to like this
const axios = require('axios');
async function getData() {
const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
}
console.log(getData());
it returns me this,
Promise { <pending> }
You cant await something outside async scope. To get expected result you should wrap your console.log into async IIFE i.e
async function getData() {
return await axios.get('https://jsonplaceholder.typicode.com/posts');
}
(async () => {
console.log(await getData())
})()
Working sample.
More information about async/await
Since axios returns a promise the async/await can be omitted for the getData function like so:
function getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}
and then do same as we did before
(async () => {
console.log(await getData())
})()
your function getData will return a Promise.
So you can either:
await the function as well to get the result. However, to be able to use await, you need to be in an async function, so you need to 'wrap' this:
async function callAsync() {
var x = await getData();
console.log(x);
}
callAsync();
(I named the function for sake of clarity, but in this scenario, one would rather use an anonymous function call; see TheReason's answer.)
or
use the result as a normal Promise, which is what an async function returns.
You have to use then with a callback:
getData().then(x => {
console.log(x);
});
The other answers have covered this fine; but I'd like to chip in and say get in the habit of creating and calling a main function rather than run things in the global scope. i.e.
async function main(){
let result = await getData();
}
main().catch(console.log);
This is pretty clear to anyone reading your code that this is your app entry point

await (async ():Type => {return value})() :: error Cannot find name 'await'.ts(2304)

// Does not work - Cannot find name 'await'.ts(2304)
let someVariable = await (async ():someType => {
// i need to use await inside here so i need it async
return someValue;
})();
// does work, but not async.
let someVariable2 = (():someType => {
// cant use await inside
return someValue
})();
i tried wrapping await inside another set of curved brackets, still doesnt work. yes i know i can declare a function then call it like you would normally, but i'd rather have it like this. if it isnt possible then ill go back to the normal way.
i do not know fully what () does in cases like this, but im assuming it returns the object inside. is it possible to use async/await like this? if possible would also like to learn more about how () works in cases like this.
code runs on Deno
edit: people saying "await must be used inside an async block" Deno has top-level await.
Clarifying.
// this is top-level
async function somefunc() {}
await somefunc(); // this WORKS on deno.
issue is let var = await(async () => {})() creates said error, and i am trying to find a way to fix this with a other way than declaring then await it
edit: https://github.com/microsoft/TypeScript/issues/38483
await can only within an async block. Make sure outside await is also within an async block or you can save the promise within someVariable.
let someVariable = (async ():someType => {
return someValue;
})();
someVariable.then((result) => {
// result contains whatever u returned in the async block.
})
const someVariable = (async () => {
const result = await Promise.resolve('Hey there!')
return result;
})()
someVariable.then(result => console.log({ result }))
Await has to be called inside a async function.
const aFunc = async () =>{
let someVariable = await (async ():someType => {
const someValue = await asyncFunc()
return someValue;
})();
// Now you get the value
console.log(someVariable)
}
aFunc()
Now You can call aFunc function to make it work

Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function? [duplicate]

This question already has answers here:
Async function without await in JavaScript
(4 answers)
Closed 2 years ago.
due to everyone's help, I got the logic behind async, promise, then, await.
I have one curisosity on top of its basic nature, which is what if
I declare async function but doesn't use await in it.
technically every argument within async function is invisibly capsulated by '.then()'
but how it works would be exactly same as synchronous function execution.
For example,
async function trackUserHandler() {
var positiondata= await getPosition();
var timerdata = await setTimer(2000)
console.log(positiondata, timerdata);
setTimer(1000).then(() => {
console.log('Timer done!');
});
console.log('one');
}
The console below doesn't run till the first two await function is done due to await(s) sitting before this.
console.log(positiondata, timerdata);
What if I don't put any await(s) in the async like below?
async function trackUserHandler() {
var positiondata= getPosition();
var timerdata = setTimer(2000)
console.log(positiondata, timerdata);
setTimer(1000).then(() => {
console.log('Timer done!');
});
console.log('one');
}
I test-run this code and behaves seemigly same as regular function without 'async'.
Of course behind the scene, everything in the function is encapsulated into 'then()' though.
Am I understanding right?
Thank you in advance.
Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function?
Yes, you are right. An async function without an await expression will run synchronously and would be identical with normal function, but the only difference is that 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.
For example, the following:
async function foo() {
return 1
}
...is equivalent to:
function foo() {
return Promise.resolve(1)
}
If there is an await expression inside the function body, however, the async function will always complete asynchronously.
For example:
async function foo() {
await 1
}
...is equivalent to:
function foo() {
return Promise.resolve(1).then(() => undefined)
}
Code after each await expression can be thought of as existing in a .then callback.
Yes, an async function runs synchronously till the first await, so it behaves like a regular function. It does return a Promise though:
function trackUserHandler() {
// ... code
return Promise.resolve(undefined);
}
In your example, the 2 functions won't behave the same. Without the await keyword, your variables won't capture the results returned by these 2 functions, but instead receive 2 Promises.
var positiondata = getPosition();
var timerdata = setTimer(2000);
So your console.log will print out 2 Promises instead of the values you actually expect.
An async function can contain an await expression, that pauses the
execution of the async function and waits for the passed Promise's
resolution, and then resumes the async function's execution and
returns the resolved value.
As you assumed, if no await is present the execution is not paused and your code will then be executed in a non-blocking manner.
const getPromise = async (s) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(s), 500);
});
}
(async() => {
try {
const result = getPromise("a"); //no await, result has not been unwrapped
console.log('async/await -> ', result);
} catch (err) {
console.log(err);
}
})();
Async function without await in Javascript

Async function returns a pending promise even though "await" is present [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
How can I return the value from an async function?
I tried to like this
const axios = require('axios');
async function getData() {
const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
}
console.log(getData());
it returns me this,
Promise { <pending> }
You cant await something outside async scope. To get expected result you should wrap your console.log into async IIFE i.e
async function getData() {
return await axios.get('https://jsonplaceholder.typicode.com/posts');
}
(async () => {
console.log(await getData())
})()
Working sample.
More information about async/await
Since axios returns a promise the async/await can be omitted for the getData function like so:
function getData() {
return axios.get('https://jsonplaceholder.typicode.com/posts');
}
and then do same as we did before
(async () => {
console.log(await getData())
})()
your function getData will return a Promise.
So you can either:
await the function as well to get the result. However, to be able to use await, you need to be in an async function, so you need to 'wrap' this:
async function callAsync() {
var x = await getData();
console.log(x);
}
callAsync();
(I named the function for sake of clarity, but in this scenario, one would rather use an anonymous function call; see TheReason's answer.)
or
use the result as a normal Promise, which is what an async function returns.
You have to use then with a callback:
getData().then(x => {
console.log(x);
});
The other answers have covered this fine; but I'd like to chip in and say get in the habit of creating and calling a main function rather than run things in the global scope. i.e.
async function main(){
let result = await getData();
}
main().catch(console.log);
This is pretty clear to anyone reading your code that this is your app entry point

Wait for deep async await results from deep function calls? [duplicate]

This question already has answers here:
Using async/await with a forEach loop
(33 answers)
Closed 6 years ago.
I'm using async await via babel-plugin-transform-async-to-generator.
At the top-level I'm awaiting a function response. Then there another two async functions func1 and func2. func2 asynchronously retrieves the content of https://www.google.com.
The following script returns:
go() called
func1() called
finished
func2() called
func2() called
func2() called
How can I only console.log('finished') after all call are executed successfully? Is it possible without returning them explicitly as Promises using resolve/reject?
This example is greatly simplified. What I'm trying to do involves recursive function calls I'd to await as well
const rp = require('request-promise')
go()
async function go() {
console.log("go() called")
await func1([1,2,3])
console.log("finished the script")
}
async function func1(arr) {
console.log("func1() called")
arr.forEach(async function(element) {
await func2()
})
}
async function func2() {
var res = await rp('https://www.google.com')
console.log("func2() called")
}
I'm still not sure how to do this for recursive calls but will create a separate question / example for it.
The above example can be fixed by using for..of instead of forEach. The inner functions results can't be awaited.
const rp = require('request-promise')
go()
async function go() {
console.log("go() called")
await func1([1,2,3])
console.log("finished the script")
}
async function func1(arr) {
console.log("func1() called")
for (let item of arr) {
await func2()
}
}
async function func2() {
var res = await rp('https://www.google.com')
console.log("func2() called")
}

Categories