Below the Radar
Below the Radar

Reputation: 7635

Promise.all() - How to resolve() without returning undefined or value

I want to use Promise.all() to check if a value is in an array. My problem is when the value is not found in the array, the promise returns undefined, but I would like to only have the values that was found in my array.

var array = [1,5,10];
var values = [1,2,3,4,5,6,7,8,9,10];
var foundValues = [];

values.forEach(function(value) {
    foundValues.push(isInArray(array, value));
});

Promise.all(foundValues).then(function(values) {
    console.log(values) // [1, undefined, undefined, undefined, 5, undefined, undefined, undefined, undefined, 10 ]
});

function isInArray(array, value) {
    return new Promise(function(resolve, reject) {
        if (array.indexOf(value) > -1) {
            resolve(value); //here the value is returned
        } else {
            resolve(); //here undefined is returned
        }
    });
};

Edit: The question is not really about finding a value in an array, I just choose this simple example to illustrate my question.

Upvotes: 2

Views: 4400

Answers (2)

I think it's not possible to make Promise.all to do that. There is no feature like that in JavaScript Promise. A Promise cannot resolve or reject without a value.

Can this code answer your question: values.filter(value => value !== undefined);(Chrome, Opera, Safari, Firefox(in-use version), and IE 9+ support Array.prototype.filter.)?

Upvotes: 3

Matt
Matt

Reputation: 44058

This doesn't seem to be possible. I would file it away as a "sane default", because it is very easy to opt-in to the behavior you want, but the inverse isn't true.

E.g.:

Promise.all(foundValues)
  .then(function(values) {
     return values.filter(function(value) { return typeof value !== 'undefined';});
  })
  .then(function(values) {
    console.log(values) // [1, 5, 10]
  });

Upvotes: 8

Related Questions