Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


1 Answers

Promise.all waits for an array of Promises. In your example, you are always pushing string types into an array. This obviously won't work. In your first example, you want to push the promises themselves:

array = [];


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

  array.push(one);


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

  array.push(two);

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

As long as the array contains Promise objects, Promise.all will work as expected.

like image 168
Davin Tryon Avatar answered Sep 02 '25 06:09

Davin Tryon