0

I'm trying to return a result from create_bna, it should always be the bna object and not a Promise. I don't want let foo = create_bna(); to change. Eventually I have students who have to use this and I don't want to introduce them to await and async etc. I have been going back and forth in attempting to return the bna object when it is ready from create_bna but I can't get it done.

Can someone help me, my head is full with information from today...


const create_bna = function() {

    let bna = {
        "banners": {
            // @Banner_Support_Sizes
            "supported_sizes": ["_512x128", "_128x512", "_128x64"]
        }
    };

    const origin = "http://localhost:8888/hslab.nl";

    (function(bna){
        let files = [];
        const resources = [
            origin+"/misc/hover_descriptions.json", 
            origin+"/misc/banners.json"
        ];
        resources.forEach(it => {
            files.push(fetch(it))
        });
        return Promise.all(files);
    })()
        .then(files => {
            let jsons = [];
            files.forEach(it => {
                jsons.push(it.json());
            });
            return Promise.all(jsons);
        })
        .then(jsons => {
            bna.hover_descriptions = jsons[0];
            bna.banners = Object.assign(jsons[1], bna.banners);
            // !!!
            // now the goal is to return bna to whoever called create_bna!
            return bna;
        });
    ;
    
}




window.addEventListener("DOMContentLoaded", function() {
    // I DONT want any await here or any other things that are related to async!
    let foo = create_bna();
    console.log(foo);
});


clankill3r
  • 9,146
  • 20
  • 70
  • 126
  • 3
    Impossible. An async function only returns a promise. The only way to consume it is asynchronously. If you don't want `await`, then all you're left with is the promise API. You can convert the function to a synchronous one if you return some hardcoded data. The other alternative to avoid exposing students to asynchronicity is to allow them to implement a callback and not go into it - just have them write a function that receives some data and should work with it. – VLAZ Jan 21 '21 at 13:25
  • Is this your actual code? If it is the `create_bna` method is not required to be `async` else you can't make it synchronous. – Eldar Jan 21 '21 at 13:28
  • The asynchronous result will be available ***sometime later***. `foo = bar()` returns a result *right now*, synchronously. There's no way to make these two fundamentally different things work together. – deceze Jan 21 '21 at 13:29

0 Answers0