2016-02-15 30 views
1

我想使用Promise.all()来检查值是否在数组中。我的问题是当在数组中找不到值时,诺言返回undefined,但我想只有在我的数组中找到的值。Promise.all() - 如何解析()而不返回undefined或值

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 
     } 
    }); 
}; 

编辑:的问题是不是真正的数组中找到价值,我只是选择了这个简单的例子来说明我的问题。

+1

你知道有更好的方法来检查,如果一个值是一个数组,对不对? – Neil

+1

我假设你使用这个作为更复杂的异步代码的例子,但真正的问题是什么?如果你没有找到任何值,那么因为你没有任何解决方法,所以'resolve()'有什么问题? –

+0

'values = values.filter(x => typeof x!=='undefined')'? – towerofnix

回答

4

这似乎不可能。我会将它作为一个“理智的默认”来归档,因为选择加入你想要的行为是非常容易的,但反过来是不正确的。

例如为:

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

我认为不可能让Promise.all这样做。 在JavaScript中没有这样的功能Promise。 A Promise不能resolvereject没有价值。

此代码是否可以解答您的问题:values.filter(value => value !== undefined);(Chrome,Opera,Safari,Firefox(正在使用的版本)和IE 9+支持Array.prototype.filter)?