简体   繁体   中英

ReactJS - async function in useEffect doesn't wait under any condition

I have searched through possible solutions quite a bit and can't find any mistake that applies in this case. The await used inside useEffect just doesn't wait.

App.js: the data state is set only through default value and nowhere else

  const [data, setData] = useState( new Data() );

  useEffect(()=>{
    async function loadData() {
      await data.load();
    }
    loadData().then(()=>{ console.log('Loaded!') });
  }, [data])

data.js is ES6 class that has async method load():

async load() {
        let test = await fetch("https://raw.githubusercontent.com/json-iterator/test-data/master/large-file.json");
        let testJson = await test.json();
    }

Whatever I try, the.then() is triggered within a split second, while opening the same json file in browser takes a long time.

Things I tried:

  • Using null as default state and instead initializing on mount useEffect( ()=>{setData( new Data() )}, [] ) (while adding check at top of data's useEffect to return if data is null)
  • IIFE function inside data's useEffect using just await instead of then
  • There are no fetching related warnings or errors in console, still I tried with just setTimeout instead
  • Few other probably pointless things.. I can't figure out what is wrong here.

I'm pretty sure your code is working properly, you're just being confused at the caching behavior and the browser display behavior.

Your load method fetches the data properly. It does not throw an error. Then the loadData function properly chains that Promise with the caller, and the caller's .then is chained properly too.

Loaded is logged near-immediately because the request doesn't take long to finish at all - and this occurs because, if you've fetched that particular endpoint before, it will return a locally cached version .

在此处输入图像描述

If you clear the cache, or press the "Disable cache" button in the developer tools, you should see the request take multiple seconds to resolve.

while opening the same json file in browser takes a long time.

This is because rendering that much content is expensive. It isn't necessarily downloading the data over the network - if it's only rendering the data from the disk cache , which it should, the problem is that formatting, displaying, paginating, and painting so much text takes a while to finish.

If you change this:

async load() {
        let test = await fetch("https://raw.githubusercontent.com/json-iterator/test-data/master/large-file.json");
        let testJson = await test.json();
    }

to do something else once the request finishes - such as trigger a state change and do more stuff with the data - you should see things working properly.

I have check async behaviour of your code...

useEffect(()=>(async () => {
    console.warn("1:- ", new Date());
    const resp = await fetch(
      "https://raw.githubusercontent.com/json-iterator/test-data/master/large-file.json"
    );
    const json = await resp.json();
    console.log(json);
    console.warn("3:- ", new Date());
  })(), []);
  1. Disable the catching from network tab
  2. simulate network type as a slow 3G o see the result

图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM