-
-
Save msmfsd/fca50ab095b795eb39739e8c4357a808 to your computer and use it in GitHub Desktop.
// 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)) |
You should never
return await
, just return the promise itselfreturn result.json()
as @senner007 says.That isn't very informative. Can you please explain why? I haven't directly used the async/await before...
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 json()
, that will fail unless the result is json.
@jagretz If you return await
you are returning a promise anyway (e.g. you will still have to resolve that promise wherever you use the returned "value"). The issue with this is that you have still made the code synchronous (and therefore slower) for no gain.
More info: https://eslint.org/docs/rules/no-return-await
Pertinent quote:
Inside an async function, return await is seldom useful. Since the return value of an async function is always wrapped in Promise.resolve, return await doesn’t actually do anything except add extra time before the overarching Promise resolves or rejects. The only valid exception is if return await is used in a try/catch statement to catch errors from another Promise-based function.
Learned something new and useful today. Thanks for posting @atwright147 !
How would you change the script to put the output into a variable?
How would you change the script to put the output into a variable?
use a closure.
I came up to a similar use of
fetch
, but how are you dealing with errors?async function async_fetch(url) { let response = await fetch(url) if (response.ok) return await response.json() throw new Error(response.status) }
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)
can u please tell me how to solve this
./src/useGoogleSearch.js
SyntaxError: /media/g/g-c/src/useGoogleSearch.js: Unterminated string constant (11:8)
9 | const fetchData = async () => {
10 | fetch(
11 | 'https://www.googleapis.com/customsearch/v1?key=$
| ^
12 | {API_KEY}&cx=${CONTEXT_KEY}&q=${term}'
13 | )
14 | .then(response => response.json())
@michaelnagy or use a fat arrow if you want to be fancy ;)
const fetchAsyncA = async () => await (await fetch('https://api.github.com')).json()
As far as I can tell it's not possible to use the returned data in this case. Let me know if I'm missing something.
Even more fancy :)
import fetch from 'node-fetch'
export default async (...args) => await fetch(...args)
I want to execute a synchronous json fetch call. The following code (see below). It works in principle, but not in the expected order (not synchronously, but asynchronously again).
My log expectation is 1 2 3 4 5 6 7, but I get 1 2 3 7 4 5 6
How do I meet my expectation?
console.log("1 start");
async function fetchInfo() {
let url = `https://reqres.in/api/products/3`; // only for test
console.log(" 3 fetch");
let response = await fetch(url);
console.log(" 4 response");
let data = await response.json()
console.log(" 5 return");
return data;
}
console.log("2 call fetchInfo()")
fetchInfo()
.then(data => console.log("6 response object: ...", data));
console.log("7 end / more code ...");
// 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
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
Promise
, and also, thatasync
implicitly returns aPromise