-1

This is probably dead simple, but I can't quite figure it out. I simply want to read the contexts of a text file into a variable. What I have is:

async function load(path) {
    try {
        const response = await fetch(path);
        const text = await response.text();
        return text;
    } catch (err) {
        console.error(err);
    }
}

var source_text = load(source_text_path);
console.log(source_text);

To my mind, this should work but only the pending promise is returned and not the text, thought I thought it was awaiting properly.

4
  • You need to await load because it is asynchronous (or chain it with a then) Commented Oct 11, 2022 at 15:36
  • I was also thinking this, but awaiting load when I create source_text gives this console error: await is only valid in async functions and the top level bodies of modules. Commented Oct 11, 2022 at 15:49
  • 2
    So you need to do just that - put it in an async function. If your intent is to get the value from a synchronous call even though the operation is asynchronous, then I'm afraid you need to rethink your approach, because information can't time-travel back into the synchronous call result when it arrives only later on. If this is for initialization: A common aporoach is to have these things in asynchronous init functions which some (also async) main function will call (and await) on startup. The synchronous top-level code then does main().catch(e => { console.error(e); process.exit(1) }) Commented Oct 11, 2022 at 15:54
  • Alternatively, you could change your project to use ES modules, because then (as the error suggested as well) you can use await in top-level code (because importing a module is in itself an asynchronous operation, unlike require). Commented Oct 11, 2022 at 15:56

2 Answers 2

1

You need to wait for the load method.

var source_text = await load(source_text_path);

OR

load(source_text_path).then(e => console.log(e))
Sign up to request clarification or add additional context in comments.

1 Comment

I was also thinking this, but awaiting the call to load() when I create source_text gives this console error: await is only valid in async functions and the top level bodies of modules.
1

The function is indeed awaiting as it should, but since it's async, it will always result in a Promise<things> when you return thing.

Which means you should either await it elsewhere:

var source_text = await load(source_text_path);

or then it:

load(source_text_path).then((source_text) => {
  console.log(source_text);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.