欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Array.filter中如何正確使用Async

 更新時間:2020年11月04日 15:57:46   作者:酷兒q  
這篇文章主要介紹了Array.filter中如何正確使用Async,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

1. 如何僅保留滿足異步條件的元素

在第一篇文章中,我們介紹了 async / await 如何幫助處理異步事件,但在異步處理集合時卻無濟(jì)于事。在本文中,我們將研究該filter函數(shù),它可能是支持異步函數(shù)的最直觀的方法。

2. Array.filter

該filter函數(shù)僅保留通過條件的元素。它得到一個斷言( predicate )函數(shù),并且此函數(shù)返回 true / false 值。結(jié)果集合僅包含斷言( predicate )返回 true 的元素。

const arr = [1, 2, 3, 4, 5];

const syncRes = arr.filter((i) => {
	return i % 2 === 0;
});
console.log(syncRes);
// 2,4

3. filter 結(jié)合 map 使用

這次的異步版本要復(fù)雜一些,它分為兩個階段。第一個通過斷言函數(shù)異步地映射數(shù)組,從而生成true / false 值。然后第二步是利用第一步的結(jié)果同步 filter

const arr = [1, 2, 3, 4, 5];

const asyncFilter = async (arr, predicate) => {
	const results = await Promise.all(arr.map(predicate));

	return arr.filter((_v, index) => results[index]);
}

const asyncRes = await asyncFilter(arr, async (i) => {
	await sleep(10);
	return i % 2 === 0;
});

console.log(asyncRes);
// 2,4

或單行實(shí)現(xiàn):

const asyncFilter = async (arr, predicate) => Promise.all(arr.map(predicate))
.then((results) => arr.filter((_v, index) => results[index]));

并發(fā)

上面的實(shí)現(xiàn)同時運(yùn)行所有斷言函數(shù)。通常,這很好,但是與所有其他功能一樣,它可能會使某些資源變得過分緊張。幸運(yùn)的是,由于上述實(shí)現(xiàn)依賴于此map,因此可以使用相同的并發(fā)控件。

4. filter 結(jié)合 reduce 使用

除了使用異步map與同步之外filter,異步reduce 也可以完成這項(xiàng)工作。由于它只是一個功能,因此即使沒有提供相同級別的控制,結(jié)構(gòu)也更加容易。

首先,從一個空數(shù)組([])開始。然后通過斷言函數(shù)運(yùn)行下一個元素,如果通過則將其追加到數(shù)組。如果沒有,請?zhí)^它。

// concurrently
const asyncFilter = async (arr, predicate) => 
	arr.reduce(async (memo, e) =>
		await predicate(e) ? [...await memo, e] : memo
	, []);

請注意,await predicate(e) 在 await memo 之前,這意味著這些將并行調(diào)用。

順序處理

要在調(diào)用下一個謂詞函數(shù)之前等待其結(jié)束,請更改await 的順序:

// sequentially
const asyncFilter = async (arr, predicate) => 
	arr.reduce(async (memo, e) => 
		[...await memo, ...await predicate(e) ? [e] : []]
	, []);

此實(shí)現(xiàn)等待上一個元素,然后根據(jù)斷言(...[e]或...[])的結(jié)果有條件地附加一個元素。

5. 結(jié)論

雖然異步filter是可能的,但它最初的工作方式看起來很奇怪。盡管并發(fā)控制仍然可用,但與其他異步功能相比,它們需要更多的計(jì)劃去控制它。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論