【问题标题】:Array exists 300ms later as expected数组按预期在 300 毫秒后存在
【发布时间】:2019-11-25 07:33:00
【问题描述】:

我正在从与 PouchDB 数据库连接的服务中加载一个数组。从那里我构建一个数组并将其返回给组件。

我的服务

getBooks() {
  let ar:BibleBook[] = [];

  this.db.allDocs({
    include_docs: true
  }).then(function (result) {
    result.rows.map((row) => {
      ar.push(row.doc);
      ar.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
    });
  }).catch(function (err) {
    console.log(err);
  });

  return ar;
}

我的组件

ngOnInit() {
  this.bibleBooks = this.db.getBooks();
  this.selectBibleBook(this.bibleBooks[0]);
}

问题:this.bibleBooks[0] 未定义,因为我的服务的答案在 300 毫秒后出现。我怎样才能等到this.bibleBooks 是一个有效的数组?

我不想与setTimeout() 合作。有更清洁的解决方案吗?

【问题讨论】:

  • 您不必为this.db.getBooks(); 发送await 吗?我猜这是一个async 请求
  • 是的..但是浏览器似乎比第一行更早地调用了第二行..所以我得到了未定义..
  • @eleinad - 是的,这就是异步请求的本质。

标签: arrays angular typescript ionic-framework


【解决方案1】:

这是一个async 问题。为了解释,在getBooks 中,您不会在返回ar 之前等待result。然后,当函数被调用时,数组为空。

它应该可以解决您的问题:

服务

async getBooks() {
  let ar: BibleBook[] = [];

  try {
    const result = await this.db.allDocs({
      include_docs: true
    });

    return result.rows
      .map((row) => row.doc)
      .sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);

  } catch (err) {
    console.log(err);
  }
}

组件

async ngOnInit() {
  this.bibleBooks = await this.db.getBooks();
  this.selectBibleBook(this.bibleBooks[0]);
}

【讨论】:

  • 你的异步函数在任何地方都没有await,因此代码仍然在做同样的事情。
  • 谢谢@K48,这只是一个错误。
  • @Nenroz 不错的答案,但我挑剔。使用results.forEach(...return results.map(...
  • @AluanHaddad 你是对的!我刚刚从原始问题中修复了async,但我很确定它可以优化
【解决方案2】:

使用 async/await 重写所有内容。

async getBooks() {
  try {
    const ar: BibleBook[] = (await this.db
      .allDocs({ include_docs: true }))
      .map(row => row.doc);

    ar.sort((a, b) => b.id - a.id);

    return ar;
  } catch (e) {
    console.log(e);
  }
}

async ngOnInit() {
  this.bibleBooks = await this.db.getBooks();
  this.selectBibleBook(this.bibleBooks[0]);
}

诀窍是:

  • 在您从数据库中获取数据之前,您的 getBooks() 函数不会完成,这要感谢 awaiting 数据库调用。
  • getBooks() 完成之前,您不会尝试selectBibleBook(),感谢await getBooks()

我还稍微简化了您的 .map(),以使代码更简洁。

【讨论】:

  • 是的。添加括号
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多