NotUser9123
NotUser9123

Reputation: 143

How can I make "onload" waiting for "fetch" complete?

Long story short, I'll show the code.

some.html

<html><script src="some.js"></script></html>

some.js

window.onload = () => console.log( "onload" );
(async (url, cb) => cb( await ( await fetch(url) ).json() ))
( "some.json", () => console.log( "in async" ) );

and some.html outputs:

onload
in async

I've done some works e.g. image loading in real fetch, so fetch().then() doesn't work for me.

Now my question is as title says, how can I let "onload" waiting for "fetch" complete?

Upvotes: 1

Views: 15098

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

What I think you are trying to achieve is the fetch starts before window.onload, but onload needs to wait for the fetch before doing anything else ...

const promiseOfSomeData = fetch("some.json").then(r=>r.json()).then(data => {
    console.log('in async');
    return data;
});
window.onload = async () => {
    let someData = await promiseOfSomeJsonData;
    console.log("onload");
};

Upvotes: 10

Related Questions