I
I
Ivan Zhilnikov2018-12-18 13:35:54
JavaScript
Ivan Zhilnikov, 2018-12-18 13:35:54

How to populate an array in node.js?

Tell me how can I fill in the arr array in this case, it's just empty, I display the result for the year, and AllScales is displayed

async.series (
  [
    function (callback) {
      DB.GetAllScales().then((AllScales) => {
        arrAllScales = AllScales;
        callback (null, AllScales);
      })

    },
    function (callback) {
      var arr = [];
      var TypeScales = [];
      async.eachSeries (arrAllScales,  Scales => {
        var NameScales = Scales['Name'];
         DB.GetTypeScales(NameScales).then(ArrtypeScales => {
          var Obj = {};
          Obj.NameScales = NameScales;
          Obj.TypeScales = ArrtypeScales;
          arr.push(Obj);
          console.log(arr.length)
        })
      })
      callback (null, arr);
    },
  ],
  function (err, result) {
    console.log (result);
  }
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Interface, 2018-12-18
@Interface

Apparently you have mixed promises and async library https://www.npmjs.com/package/async .
I agree with shmatuan that it would be best to use async/await. If this is not possible, I advise you to rewrite to one thing, either callbacks or Promises (the second is better, of course).
Judging by the code, the problem is that the callback in which the array is replenished is asynchronous. This means that we will exit the external function before it is executed. This means that the next callback in async.series will be executed with an empty array.
Ivan Zhilnikov Here is one of the solutions to the problem:
https://jsfiddle.net/int0h/17bojhfm/
That is, using Promise.all
At the end there is an async / await solution, it does about the same as yours, but it reads much better and takes 10 lines, not 30. Spoiler, here it is:

async function main() {
    const scales = await DB.GetAllScales();
    const result = await Promise.all(
        scales.map(async scale => ({
            TypeScales: await DB.GetTypeScales(scale.Name),
            NameScales: scale.Name
        }))
    );
  console.log('async / await result:', result);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question