Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 124 Vote(s) - 3.56 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to return values from async functions using async-await from function?

#1
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> }
Reply

#2
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_
Reply

#3
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`](

[To see links please register here]

) sample.

More information about [`async/await`](

[To see links please register here]

)

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())
})()
Reply

#4
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:

```javascript
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][1].)


or

* use the result as a normal Promise, which is what an async function returns.
You have to use `then` with a callback:

```javascript
getData().then(x => {
console.log(x);
});
```


[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through