Quoc Tran
Quoc Tran

Reputation: 45

What's the correct way to pause the entire script execution contingent on an asynchronous function in JavaScript?

A lot of my script is contingent on information first read from a .JSON file using fetch() and .json() so it's asynchronous. I need to delay the execution of the rest of my script until those functions finish, without sticking the rest of my code in a huge .then() or function block or something. I've done some searching around but I can't really find what I'm looking for.

let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json);

console.log(config);
// REST OF SCRIPT

It should log the config JSON object or the promise but, obviously, it only returns undefined. Any help would be greatly appreciated!

Upvotes: 0

Views: 147

Answers (3)

Ziv Ben-Or
Ziv Ben-Or

Reputation: 1194

you can use this:

fetch(chrome.runtime.getURL("../config.json"))
    .then(response => response.json())
    .then(config => console.log(config));

Or:

const response = await fetch(chrome.runtime.getURL("../config.json"));
const config = await response.json();
config => console.log(config)

Upvotes: 0

Mark
Mark

Reputation: 92440

You only have one thread to work with, so there's no getting around the fact that you need to perform the async fetch of you config and then get on with the rest of your program. Most javascript is event driven, so this isn't typically a big issue. You can write in a style where the primary entrance to your code is a main() function, then you can just call it with the config after it's fetched:

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(main);

function main(config){
  // do stuff


}

Any substantially large code-base will be refactored into smaller functions anyway, so ideally your main function should not really be that large to begin with.

Upvotes: 0

Vaughan Hilts
Vaughan Hilts

Reputation: 2879

Your config is being read before the request comes back. You can add another then clause:

let config;

fetch(chrome.runtime.getURL("../config.json"))
  .then(response => response.json())
  .then(json => config = json)
  .then(() => {
     console.log(config);
   });

Upvotes: 1

Related Questions