[英]How to use promises to continue operation
我需要在一個大型JSON文件中搜索id
然后返回所有屬性。 但是,有一個parentId
屬性。 這對應於我需要包含其屬性的另一個對象的id
,並且可能對應於另一個parentId
等。
m.getAttrs = function(o){
var a = []
// get the model based on id or object.id
if(o instanceof String)
var obj = json.models.filter(i => i.id == o)[0]
else
var obj = json.models.filter(i => i.id == o.id)[0]
////// On 2nd iteration: "TypeError: Cannot read property 'hasOwnProperty' of undefined" ///////////////
if( obj.hasOwnProperty("parentId") && obj.parentId != ""){
// get parent id
var pid = obj.parentId
// get parent attributes
a.push(m.getAttrs(pid)) // RECURSION //
}
// get attributes
var attrs = obj.attrids
// get Attribute Names
for(aid in attrs){
var aName = json.attrs.filter(i => i.id == aid)
a.push(aName)
}
return a
}
我看到其中一個錯誤 obj
不getAttrs 的第一次迭代后確定。 我認為這是因為json.models.filter...
尚未完成,但是可能有很多事情。
我已經嘗試了很多次來實現Promise,但是似乎無法使任何工作正常進行,這使我的代碼太亂了,以至於我不想在這里包含它。
我如何實現承諾:“找到正確的模型后, 繼續 (而不是執行其他功能)”?
這是我發現的...
Array.prototype.filter
是同步的,因此我的問題不是與異步有關的。 事實證明,除非您專門創建一個String變量,否則instanceof String
不起作用。 這是我發現可以提供幫助的帖子: 為什么instanceof對某些文字返回false? 這修復了我的代碼:
if(typeof o === "string")
var obj = json.models.filter(i => i.id == o)[0]
else
var obj = json.models.filter(i => i.id == o.id)[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.