1

In the main function I want to call a series of functions that need to wait for the previous one to finish first.

I want my console to output: A, B, B, B, B, C, D. Where B would appear a few times for each item in snapPivot.

The result I get now is: A, C, D, B, B, B, B

It seems that the getPivot function is not waiting for the inner loop to finish. How can I make sure the getPivot function first finishes the inside loop with the console.log('b') before continuing to console.log('c') and console.log('d')

main function:

    dashboardListner
      .child(activeDashboardId)
      .child('widgets')
      .once('value', snap => {
          widgets = snap.val();
      })
      .then(thenWidgets => {
        async function asyncCall() {
          console.log('A');
          Object.entries(thenWidgets.val()).map(async function(widget) {
            return await getPivot(widget, userId);
          });
          console.log('C');
        }
        return asyncCall();
      })
      .then(pivotData => {
        async function asyncCall2() {
          console.log('D');
          return await getMain(pivotData);
        }
        return asyncCall2();
      })

getPivot function:

const getPivot = (widget, userId) => {
  return new Promise(resolve => {
    const pivotData = {};
    //Get get pivot table name
    const pivotName =
      'user' + widget[1].type.charAt(0).toUpperCase() + widget[1].type.slice(1);

    //Get pivot data into widget object
    const pivotRef = firebase
      .database()
      .ref()
      .child(pivotName)
      .child(userId);

    pivotRef
      .once('value', snapPivot => {
        return Promise.all([
          snapPivot.forEach(function(result) {
            if (result.val().widgetId === widget[0]) {
              pivotData[result.key] = result.val();
              console.log('B');
            }
          }),
        ]);
      })
      .then(() => {
        resolve(pivotData);
      });
  });
};
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
2hTu2
  • 378
  • 4
  • 19
  • 1
    `return Promise.all([ snapPivot.forEach() ]` - you're not actually waiting for anything here, since `Promise.all` expects an array of Promises but `forEach` doesn't return anything. – VLAZ Nov 19 '19 at 22:24
  • @VLAZ good point, what would you recommend to make sure the loop will finish before continuing? – 2hTu2 Nov 19 '19 at 22:26
  • You shouldn't use `.map()` when you're not using the result, e.g. `Object.entries(...).map()`. You use `forEach()` when you don't need the result, `.map()` when you want a list of all the results. – Barmar Nov 19 '19 at 22:27
  • I'm finding it hard to track down exactly what's happening. It doesn't seem like it's doing anything async, so I'm not sure why you want to treat it as a Promise. – VLAZ Nov 19 '19 at 22:27
  • So my goal is to make sure the order is A, B, C, D and not A,C,D,B. I thought that using async functions is the correct way, but something is not correct. So perhaps I am doing something wrong here? – 2hTu2 Nov 19 '19 at 22:34
  • 1
    Those `asyncCall` functions make no sense. Just inline them! – Bergi Nov 19 '19 at 22:35
  • @Bergi can you give me an example? – 2hTu2 Nov 19 '19 at 22:38
  • 1
    @2hTu2 `async (thenWidgets) => { console.log('A'); const pivotData = await Promise.all(Object.entries(thenWidgets.val()).map(widget => getPivot(widget, userId))); console.log('C'); console.log('D'); return getMain(pivotData); }` – Bergi Nov 19 '19 at 22:42
  • The following part is not doing what you'd expect: ```javascript Object.entries(thenWidgets.val()).map(async function(widget) { return await getPivot(widget, userId); }); // fire and forget some promises (and never reference them) ``` - Transform an array of values to an Array of `Promise` - Do nothing with this array of promises. What you intended to do here is: ```javascript await Promise.all( Object.entries(thenWidgets.val()).map(widget => getPivot(widget, userId)) ) // all getPivot calls are now resolved. ``` – ifroz Nov 19 '19 at 22:46
  • The example @Bergi commented here seems to be a good setup. It now return A, B, B, B, C, D. I can study this example from here out. Thanks for the help. The question can be closed. – 2hTu2 Nov 19 '19 at 22:51

0 Answers0