Typescript在对象上返回undefined

时间:2017-04-22 08:53:16

标签: angular typescript pouchdb

我有以下代码。我从Express Pouchdb中拉出对象,然后遍历_attachments键以拉出所有附件。我有两个附件:“index”和“toc”。有趣的部分是“索引”返回它的“数据”属性罚款,但这一个保持失败,我不知道为什么。这就是我将“toc”设置为我的文章对象的方式。

Object.keys(new_article['attachments']).map((at) => {
    this.articleStore.getAttachment(new_article['id'],at).then ((res) => {
        new_article.attachments[at]['data'] = res.toString();
    });
});

if (new_article['attachments'].hasOwnProperty('toc')) {
    console.log(new_article['attachments']['toc']) //Line #27 in screenshot
    console.log(new_article['attachments']['toc'].data) //Line #28 in screenshot
    new_article.toc = new_article['attachments']['toc']['data'];
}

以下是控制台的屏幕截图: screenshot of console

PouchDB中的同一个对象:

{
  "_id": "8c0f586b-020b-4832-bcde-945421c22a2e",
  "description": "Getting the Gist of Markdown's Formatting Syntax",
  "author": "John Gruber",
  "title": "Getting the Gist of Markdown's Formatting Syntax",
  "date": "4/15/2017",
  "_attachments": {
    "index.md": {
      "digest": "md5-PjR3R2K+KdpgLy/ye5wgAA==",
      "content_type": "application/octet-stream",
      "length": 8373,
      "revpos": 5,
      "stub": true
    },
    "toc": {
      "digest": "md5-heDcEdGg7nzo0OKe/30YxQ==",
      "content_type": "application/octet-stream",
      "length": 130,
      "revpos": 6,
      "stub": true
    }
  },
  "_rev": "8-167fdf2e930304927c5e2fc4e371b123"
}

这里的整个项目=> https://github.com/flamusdiu/micro-blog/tree/dev

修改1

当我从pouchdb中提取对象时,

_attachments被重新映射到attachments。更新了代码以显示其上方的行。

编辑2 从异步调用返回值工作正常。这一部分没有错。看起来它链接到我的第二个电话是修复它的原因。见下面的答案。

1 个答案:

答案 0 :(得分:0)

数据库查询是一个异步调用,循环中的赋值不会在结尾之前执行。试试这个:

Promise.all(Object.keys(new_article['attachments']).map((at) => {
    return this.articleStore.getAttachment(new_article['id'],at).then ((res) => {
        new_article.attachments[at]['data'] = res.toString();
    });
})).then(() => {
    if (new_article['attachments'].hasOwnProperty('toc')) {
        console.log(new_article['attachments']['toc']) //Line #27 in screenshot
        console.log(new_article['attachments']['toc'].data) //Line #28 in screenshot
        new_article.toc = new_article['attachments']['toc']['data'];
    }
});