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")
}
Related
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
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
If I have two functions and the parent function (function Two) is marked as async and uses the await keyword when calling One, will the code inside function One() run async or do both functions need to be marked as async.
function One(){
// Asynchronous Code
}
async function Two(){
await One();
}
The function that uses await must be async.
The value that you await needs to be a Promise (or the await is pointless).
Functions marked as async always return Promises, but that's only a useful way to create a Promise if you are using await inside it.
As long as the function One() returns a promise, you can await its return value. So you don't necessarily need to mark One() as async.
For example:
function One() {
return new Promise(resolve => setTimeout(resolve, 500, 42))
}
async function Two(){
console.log("Calling One()...")
let ret = await One();
console.log("One() returned:", ret)
}
Two()
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
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