Promise.all() - 如何在不返回 undefined 或 value 的情况下解析()

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

本文关键字:value undefined 情况下 all Promise 返回      更新时间:2023-09-26

我想用Promise.all()来检查值是否在数组中。我的问题是当在数组中找不到值时,promise 返回 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
        }
    });
};

编辑:问题并不是关于在数组中查找值,我只是选择这个简单的例子来说明我的问题。

似乎是不可能的。我会将其作为"理智的默认值"归档,因为选择加入您想要的行为非常容易,但反之则不然。

例如:

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

Promise.all这样做。在JavaScript Promise中没有这样的功能。没有值,Promise不能resolvereject

这段代码可以回答你的问题吗:values.filter(value => value !== undefined);(Chrome,Opera,Safari,Firefox(使用中版本(和IE 9+支持Array.prototype.filter(。