2016-02-15 29 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)?