Search code examples
javascriptpromisees6-promise

Javascript Promise push value into array (only from function or outside?)


I have some promises and a Promise.all:

array = [];


  var one = new Promise(function(resolve, reject) {
    // Do stuff
    setTimeout(function() {
      resolve('One Done');
      array.push('one');
    }, 5000);
  });


  var two = new Promise(function(resolve, reject) {
    // Do Stuff
    resolve('Two Done');
    array.push('two');
  });


  Promise.all(array).then(values => {
    console.log(values);
  });

We know this doesn't work because array.push needs to be outside.

I currently have a few functions which I need to have called by promises so that finally I can have it in Promise.all.

Would it be advisable to call the function from inside the promise like this:

    function dosomething() {
        // does something
        array.push('something');
    }

  var mypromise = new Promise(function(resolve, reject) {
    dosomething();
    resolve('Did something');
  });

Or is there a more advisable way to do this?


Solution

  • Promise.All expects an array of promises, and will wait until all promises are fullfilled, providing you with the results of each Promise or a catch if any of them fails.

    You can resolve them with any type of object if you are willing to resolve it with more than just a string, and you can use the results afterwards in any way you want, so you could avoid messing with the array inside from the promise and instead resolve the "work item" as a unit and use all required results after the async evaluation.

    This will also ( i think ) make the code cleaner and more managable.

    You could instead try to do this:

       var valuesArray=[];
    
       var prom1 = new Promise(function(resolve, reject) {
            // Do stuff
            setTimeout(function() {
              resolve({ msg: 'One Done', data : 'one'});
              // array.push('one');
            }, 5000);
          });
    
        var prom2 = new Promise(function(resolve, reject) {
            // Do Stuff
            resolve({ msg: 'Two Done', data : 'two'});
            // array.push('two');
          });
    
       var promisesArray= [prom1,prom2]; 
    
       Promise.all(promisesArray).then(values => {
            // do stuff with values here
            console.log(values[0].msg);
            console.log(values[1].msg);
            valuesArray.push(values[0].data);
            valuesArray.push(values[0].data);
          });