Arfons Arfons - 6 months ago 93
JSON Question

Get return from function and then use in promise.all()?

I have three functions each of which performs a SQL query and returns me an array of data; I know this part is working because I can do a json.stringify before returning the array and it works as intended. The problem is that I need to wait until these three functions finish and then do some more stuff with them.

Each function I use has this same call structure: => {
fooJSON = '{foo:[' + JSON.stringify(fooStorage) + ']}';

I'm aware I should have an array of promises and then push the promises to it and then use Promise.all(), but I don't really know what part of the code I'd actually have to do that on.

Edit: Clearing up, each makeFullJSON() I call returns a promise ( of an array ). I need to do stuff with that resulting array.


Assign the promise to a variable when you create it, and then you can pass that variable into promise.all().

Since I cannot see the full implementation of your code, here is a working, slimmed down version of how this works with promises, mocked with some similar names.

function makeFullJSON(time) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, time, [time]); // send back an array for simulation

var p1 = makeFullJSON(1000);
var p2 = makeFullJSON(500);
var p3 = makeFullJSON(750);

p1.then(array => {
  console.log('Promise 1 complete', array);
  // Do other stuff with the return value

p2.then(array => {
  console.log('Promise 2 complete', array);

p3.then(array => {
  console.log('Promise 3 complete', array);

  .all([p1, p2, p3])
  .then(arrayOfAllResolvedValues => {
    // This array will contain values; the values from the
    // resolved promises in order of adding them to the promises array
    console.log('Array of resolved values:', arrayOfAllResolvedValues);