我想使用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
}
});
};
编辑:的问题是不是真正的数组中找到价值,我只是选择了这个简单的例子来说明我的问题。
你知道有更好的方法来检查,如果一个值是一个数组,对不对? – Neil
我假设你使用这个作为更复杂的异步代码的例子,但真正的问题是什么?如果你没有找到任何值,那么因为你没有任何解决方法,所以'resolve()'有什么问题? –
'values = values.filter(x => typeof x!=='undefined')'? – towerofnix