Promise.all() - 如何在不返回 undefined 或 value 的情况下解决 () [英] Promise.all() - How to resolve() without returning undefined or value

查看:55
本文介绍了Promise.all() - 如何在不返回 undefined 或 value 的情况下解决 ()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Promise.all() 来检查一个值是否在数组中.我的问题是当数组中找不到值时,promise 返回 undefined,但我只想拥有在我的数组中找到的值.

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

这个问题并不是关于在数组中找到一个值,我只是选择这个简单的例子来说明我的问题.

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

推荐答案

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

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.

例如:

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() - 如何在不返回 undefined 或 value 的情况下解决 ()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆