[英]Typescript returns undefined on object
我有以下代碼。 我從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'];
}
來自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從異步調用返回值工作正常。 這一部分沒有錯。 看起來它鏈接到我的第二個電話是修復它的原因。 見下面的答案。
DB查詢是異步調用,循環中的賦值不會在if之前執行。 嘗試這個:
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'];
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.