-1

I'm trying to resolve promises from a nested for loop:

let fillInTable = () => {
    let result = []
    $.getJSON(`https://kvdb.io/${bucket}/?format=json`).then((data) => {
       data.map(each => $.getJSON(`https://kvdb.io/${bucket}/${each}`).then(o => {
          result.push(o)
       }));
    });
    return result
}

let random = fillInTable(); // appears to be []

// TODO: Wait for random to receive all the information from fillInTable() before executing anything else

The random is always empty, which I guess by default getJSON is async. I'm trying to use await but it doesn't work since it's not in an async function.

I tried to push all promises in an array and then use Promise.all([...]) but doesn't work either.

Does anyone have a solution?

AustinP
  • 63
  • 6
  • just `return $.getJSON(...)`.. within that you can use `return Promise.all(...)` then use `fillInTable().then(result => ...)` to handle the final result. – Đinh Carabus Feb 13 '20 at 23:51

1 Answers1

1

I've replaced the two URLs with some dummy JSON endpoints, in order to make this work. It should be working with your own endpoints also.

let fillInTable = async () => {
    const data = await $.getJSON(`https://api.myjson.com/bins/awyt4`);
    const result = await Promise.all(
        data.map( each => $.getJSON(`https://jsonplaceholder.typicode.com/posts?id=${each}`) )
    );
    return result
}


fillInTable()
.then( random => console.log( random ))
.catch( error => console.error( error )); // Always handle rejections in Promises ;)
Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25