0
const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
// letters container 
const lettersContainer = document.querySelector(".letters");
// add each alphabet into lettersContainer
letters.forEach(letter => {
    // create span for letter
    let span = document.createElement("span");
    let spanText = document.createTextNode(letter);
    span.appendChild(spanText);
    lettersContainer.appendChild(span);
})
console.log("before getData")
// fetch words and category
async function getData(src) {
    try {
        let data = await fetch(src);
        data = await data.json();
        console.log(data)
        return data
    } catch (error) {
        console.log(error)
    }
}
// words.json is json that contain simple object of words
let wordsAndCategory = getData("./words.json");
console.log("after getData");
//the rest of code depends on object wordsAndCategory

when i execute code, it prints after getData before printing data. i have another solution which is putting the rest of code in async function but i am wondering if there is a better solution for this issue.

  • 2
    How about getData("...").then( function(wordsAndCategory){ Rest of code that depends on wordsAndCategory }); – Kostas Minaidis Jun 23 '23 at 19:32
  • *"it prints after getData before printing data"* - Because `getData()` is `async`, and it is not being `await`-ed. By contrast, note how you `await` the `async` operations *within* `getData()`. – David Jun 23 '23 at 19:45
  • @David but how to await for it outside a async function? – Abdulaziz Jun 23 '23 at 20:03
  • If your environment doesn't support top-level await then you either need to wrap everything in an async function or encapsulate it in a `.then`. Once in async land always in async land. – pilchard Jun 23 '23 at 20:05
  • @Abdulaziz: Either wrap it in an `async` function or append `.then()` to the `Promise` returned by the `async` function. – David Jun 23 '23 at 20:05

1 Answers1

0

The async getData function returns a promise. You can either await that call or use a .then callback to resolve the promise before printing the statement. To use await you’ll need to move all of the code inside an async function itself. Usually a “run” function. Then try:

let wordsAndCategory = await getData("./words.json");
console.log("after getData");
samsmi7h
  • 31
  • 4
  • let wordsAndCategory = await getData("./words.json"); This will cause error because you can not await outside of async function, am i right? – Abdulaziz Jun 23 '23 at 20:01
  • Yes, if you want to use the `await` approach you need to put your code in an async function (or be in an environment that allows top-level await) – Nicholas Tower Jun 23 '23 at 20:48