0
$('#search-form').submit(async () => {
    var urls = await FetchUrls();
    console.log(urls);
});

function FetchUrls() {
    var array = [];
    return new Promise((resolve, reject) => {
        $.getJSON("list.json", (json) => {
            $.each(json, (index, field) => {
                categories.forEach((item) => {
                    if (item === field.major) {
                        array = array.concat(field.x);
                        array = array.concat(field.y);
                    }
                });
            });
        });
        resolve(array);
    });
}

Why that doesn't wait for FetchUrls return?

I use await keyword for that.

It logs urls before urls get filled.

John Doe
  • 3
  • 1
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) and instead use the promise that `$.getJSON` returns! – Bergi May 07 '20 at 21:52
  • 1
    You need to put your `resolve()` in the callback you pass to `$.getJSON()`. The way it is now it resolves immediately. – Lennholm May 07 '20 at 21:54
  • @Bergi May you give me some example,, please? – John Doe May 07 '20 at 22:41
  • @JohnDoe https://stackoverflow.com/a/31327725/1048572 – Bergi May 08 '20 at 07:32

0 Answers0