【问题标题】:Async problems whith Array.filterArray.filter 的异步问题
【发布时间】:2016-12-21 12:54:31
【问题描述】:

我正在使用 Ionic2 / Angular2typescript,但我在过滤数组时遇到了问题。

我有

let localTours = [];
...
let newTours = dbTours.filter(x => localTours.indexOf(x) < 0);
localTours.push(newTours);

在此示例中,我的 localTours 始终为空,因为在过滤之前调用了 .push。知道如何解决这个问题吗?

【问题讨论】:

  • 过滤器不是问题,something() 可能是。请显示该功能。您显示的代码中没有任何内容是异步的
  • 实际上代码是这样的:let newTours = dbTours.filter(x =&gt; localTours.indexOf(x) &lt; 0);,然后是localTours.push(newTours);。我将更新问题中的代码。
  • 更新您的代码以包含 localTours 的来源。
  • dbTours 怎么样?那是一个数组,还是一个 db 对象?类似于 ORM 的东西?而filter方法其实是在逆db?
  • 这是我订阅Observable&lt;Tour[]&gt;的数组。

标签: javascript angular asynchronous typescript array-filter


【解决方案1】:

要么你的过滤是错误的并且正在过滤所有东西,因此给你一个空数组,或者你的东西函数是异步的,在这种情况下,你会受益于使用类似 async.js 库之类的东西:

oneArray.filter(something, (err, results) => {
   otherArray.push(results);
});

你的东西功能,看起来像:

function something(item, callback) {
  //your filtering logic needs to call the callback function to move onto the next item
}

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 2018-12-09
    • 2017-01-09
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2010-12-16
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多