-1

I'd like to have the loadConfig function async and just finish after the resource has been loaded. await fetchetc. How can I declare it in this object syntax as an async function?

var QMEM = QMEM || {
    config : null,
    loadConfig : function(url) {
        console.log('url = ', url);
        fetch(url)
        .then(res => res.json())
        .then(out => {
            this.config = out;
        })
        .catch(err => console.log(err));
    },
    logConfig : function() {
        console.log('current configuration:\n', this.config);
    }
};
QMEM.loadConfig(myConfigUrl);
QMEM.logConfig();
5
  • 3
    Put the keyword async before function? Is that what you're asking? Commented Jul 9 at 15:23
  • Tried that, gave me a "bad invocation error, expected function or {" Commented Jul 9 at 15:24
  • 4
    Please edit your question to show exactly what you tried. Commented Jul 9 at 15:26
  • 2
    @rhavin does the environment you're running this JS code in support async operations? Also note that this in the final then call will not be a reference to the outer object. You'll need to amend the scope Commented Jul 9 at 15:29
  • 1
    Don't confuse object initializers (which are part of JavaScript) with JavaScript Object Notation (which is a data format based on a subset of JavaScript). Commented Jul 9 at 15:34

1 Answer 1

1

It isn't relevant that you are assigning the function as a value of a property in an object initilizer.

You mark it as asynchronous in the same way that you mark any function expression:

async function() {
    // function body
}

So:

loadConfig : async function(url) {

Or using shorthand method notation:

async loadConfig(url) {
Sign up to request clarification or add additional context in comments.

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.