// Async/Await requirements: Latest Chrome/FF browser or Babel: https://babeljs.io/docs/plugins/transform-async-to-generator/ | |
// Fetch requirements: Latest Chrome/FF browser or Github fetch polyfill: https://github.com/github/fetch | |
// async function | |
async function fetchAsync () { | |
// await response of fetch call | |
let response = await fetch('https://api.github.com'); | |
// only proceed once promise is resolved | |
let data = await response.json(); | |
// only proceed once second promise is resolved | |
return data; | |
} | |
// trigger async function | |
// log response or catch error of fetch promise | |
fetchAsync() | |
.then(data => console.log(data)) | |
.catch(reason => console.log(reason.message)) |
This comment has been minimized.
This comment has been minimized.
@michaelnagy or use a fat arrow if you want to be fancy ;)
|
This comment has been minimized.
This comment has been minimized.
Nice way to handle network requests, keeping everything in separate files: RequestService.js
NetwrokService.js
ArticlesMain.js
|
This comment has been minimized.
This comment has been minimized.
@FilipIlievski why do you use promises in the RequestService class? |
This comment has been minimized.
This comment has been minimized.
@msmfsd is there any need to assign and return data? This works just as well... async function fetchAsync () {
const response = await fetch('https://api.github.com');
return await response.json();
} |
This comment has been minimized.
This comment has been minimized.
I came up to a similar use of async function async_fetch(url) {
let response = await fetch(url)
if (response.ok) return await response.json()
throw new Error(response.status)
} |
This comment has been minimized.
This comment has been minimized.
@gengns use try catch |
This comment has been minimized.
This comment has been minimized.
Thanks for this gist, make me better understand async/await ! |
This comment has been minimized.
This comment has been minimized.
@FilipIlievski Found the Java guy! |
This comment has been minimized.
This comment has been minimized.
@FilipIlievski I like this solution. is there any reason to have an await inside of an await? |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
if You have 2 fetch calls, its better to await the value as compared to the fetch calls themselves, because we will then let the process occur in parallel other than in sequence async function bestFetch() {
const first = fetch();
const two = fetch();
const firstvalue = await first.json();
const secondvalue = await two.json();
} Unlike the following ( below ) where the requests will happen in sequence async function badFetch() {
const first = await fetch();
const two = await fetch();
const firstvalue = await first.json();
const secondvalue = await two.json();} |
This comment has been minimized.
This comment has been minimized.
thanks @Tevinthuku. The first example is awesome. |
This comment has been minimized.
This comment has been minimized.
Example that can be easily tested with JSONPlaceholder : (async () => {
'use strict';
console.clear();
const getUser = async identifier => await (await fetch(`https://jsonplaceholder.typicode.com/users/${identifier}`)).json();
try {
const firstUser = await getUser(1);
console.log(firstUser);
const secondUser = await getUser(2);
console.log(secondUser);
// there are 10 users in JSONPlaceholder/Users
} catch (exception) {
console.error(`Failed to retrieve user informations: (${exception})`);
}
})(); |
This comment has been minimized.
This comment has been minimized.
@gengns gets it. |
This comment has been minimized.
This comment has been minimized.
You don't need to await the json. Just return it async function fetchAsync () { Or this: async function fetchAsync () { |
This comment has been minimized.
This comment has been minimized.
You should never |
This comment has been minimized.
This comment has been minimized.
This is a little confusing. In my testing if you call fetchAsync() from a non async method it doesn't wait. For example if the testFetch method below is called, the "after fetch()" is logged before the "data retrieved is logged". Am I missing something?? Please tell me I am!!! The only way I have seen it work as expected is when the fetchAsync method is called from a ngOnInit method that is also changed to async. pubic testFetch() { async function fetchAsync () { Ideally I want the json file loaded BEFORE execution continues like implied. |
This comment has been minimized.
This comment has been minimized.
That isn't very informative. Can you please explain why? I haven't directly used the async/await before. The fetch API documentation on MDN states that fetch returns a |
This comment has been minimized.
This comment has been minimized.
Nevermind, I understand now. The fetch is async, the json method is sync. But in regards to that, I disagree with you comment that you should "never" return an await. If you wrap the fetch call in another function, you can abstract the call and have the calling code be responsible for accessing the response, may it be json, a blob, or something else. If, as you stated, you explicitly return the result by calling |
This comment has been minimized.
This comment has been minimized.
@jagretz If you More info: https://eslint.org/docs/rules/no-return-await Pertinent quote:
|
This comment has been minimized.
This comment has been minimized.
Learned something new and useful today. Thanks for posting @atwright147 ! |
This comment has been minimized.
This comment has been minimized.
How would you change the script to put the output into a variable? |
This comment has been minimized.
This comment has been minimized.
use a closure. |
This comment has been minimized.
This comment has been minimized.
In addition to use try .... catch blocks, it is better to put the above code (by @gengns) inside the try block because "The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing." (quoted from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) |
This comment has been minimized.
This comment has been minimized.
can u please tell me how to solve this ./src/useGoogleSearch.js 9 | const fetchData = async () => {
|
This comment has been minimized.
Hi, you also can write this function to a more concise way like this:
async function fetchAsync () {
let data = await (await fetch('https://api.github.com')).json();
return data;
}