Javascript筛选器方法返回原始数组,即使返回false也是如此
我有一个过滤方法,如下所示:Javascript筛选器方法返回原始数组,即使返回false也是如此,javascript,typescript,async-await,es6-promise,array-filter,Javascript,Typescript,Async Await,Es6 Promise,Array Filter,我有一个过滤方法,如下所示: let newArray = Alerts[symbol].filter(async (alert: IDiscordSymbolAlert, alert_index: number) => { // If Price when set is greater than alert price, price has to move UP to trigger if (alert.price_when_set < al
let newArray = Alerts[symbol].filter(async (alert: IDiscordSymbolAlert, alert_index: number) => {
// If Price when set is greater than alert price, price has to move UP to trigger
if (alert.price_when_set < alert.alert_price) {
hasToGo = Change.UP;
}
// If Price when set is greater than alert price, price has to move DOWN to trigger
else if (alert.price_when_set > alert.alert_price){
hasToGo = Change.DOWN;
}
/**If the hasToGo is UP and current price is greater than alert price, then ALERT USER [OR]
// If the hasToGo is DOWN and current price is lesser than alert price, then ALERT USER **/
if((hasToGo === Change.UP && (price >= alert.alert_price)) ||
(hasToGo === Change.DOWN && (price <= alert.alert_price))) {
/**
* Send Notification that alert has been hit
*/
let userToSend = await discord.users.fetch(alert.userID)
if(!userToSend) return;
//@ts-ignore
userToSend.send(`> @everyone\n\n${symbol} has reached your alert price - ${alert.alert_price}`);
// remove that alert
guild_modified = true;
return false;
}
return true;
});
// When logged here, it shows the entire array even though certain values have returned false.
// I know they returned false because the block in which they returned false was executed and
//i did receive a notification which was executed in the same block.
console.log(newArray);
因为过滤器在这种情况下不能与async/await
一起使用。这是我使用forEach()
循环并使用splice()
手动删除数组中的匹配对象。但是因为forEach本身是异步的,并且console.log
在异步块之外运行。它不会返回新数组,而是返回未修改的数组。如何返回要在forEach块范围之外使用的新数组
提前谢谢 您不能将
async
函数与过滤器一起使用<代码>过滤器
返回回调函数返回真实值的所有元素async
函数始终返回承诺,承诺是对象,所有非null
对象都是真实的
如果您的过滤器
检查需要是异步的
,那么您的整个操作都是异步的
,需要这样处理
这里有一个现成的async
过滤函数,它并行执行元素检查。同样,与所有async
函数一样,它返回一个结果承诺:
async function filterAsync(array, callback, thisArg = undefined) {
const flags = await Promise.all(array.map(callback, thisArg));
const result = [];
for (let n = 0; n < array.length; ++n) {
if (flags[n]) {
result.push(array[n]);
}
}
return result;
}
或
async function filterAsync(array, callback, thisArg = undefined) {
const flags = await Promise.all(array.map(callback, thisArg));
const result = [];
for (let n = 0; n < array.length; ++n) {
if (flags[n]) {
result.push(array[n]);
}
}
return result;
}
// In an `async` function (assuming you want errors to propagate):
const newArray = await filterAsync(Alerts[symbol], element => /*...keep-or-toss logic...*/);
// ...use `newArray`...
// Not in an `async` function
filterAsync(Alerts[symbol], element => /*...keep-or-toss logic...*/)
.then(newArray => {
// ...use `newArray`...
})
.catch(error => {
// ...handle/report error...
});