【发布时间】:2020-03-11 15:54:05
【问题描述】:
我有一个如下所示的数组:
"attributes": [{"id": "5dad5242e7038210842ec59c","value": 3},{"id": "5dbade6a824f3e2244b2870b","value": 6},{"id": "5d7c943a5759f91e187520cc","value": 17}]
数组中的每个值都对应一个模式,我将从中获取该数据。
例如:if(value == 1){ fetch data from schemaA}
根据从每个模式中获取的数据,我将使用附加信息重新填充数组,因此最后数组将如下所示:
"attributes": [{"id": "5dad5242e7038210842ec59c","value": 3, "name": "attributeA"},{"id": "5dbade6a824f3e2244b2870b","value": 6, "name": "attributeF"},{"id": "5d7c943a5759f91e187520cc","value": 17, "name": "attributeQ"}]
到目前为止,我已经写了一个函数:
exports.fetchAttributes = (attr, callback) => {
try {
switch (attr.value) {
case 3:
this.fetchAttributeC(attr.id, (err, attributeB) => {
callback(err, attributeB);
});
break;
case 6:
this.fetchAttributeF(attr.id, (err, attributeF) => {
callback(err, attributeF);
});
break;
case 7:
this.fetchAttributeQ(attr.id, (err, attributeQ) => {
callback(err, attributeQ);
});
break;
default : console.log("Invalid value");
}
} catch(e){
console.log("Catch in fetchAttributes "+e);
return callback(e, null);
}
}
上面的函数正在另一个函数中被调用:
exports.functionAttributes = (attributes, callback) => {
let newAttributes = [];
attributes.forEach((attr) => {
this.fetchAttributes(attr, (err, attributeFull) => {
newAttributes.push(attributeFull);
})
}
//need to pass in callback here, but obviously there is a scope issue
}
我需要这个带有 newAttributes 的数组,因为我必须将它传递给这个函数所在的异步瀑布中的最终回调。由于范围问题,newAttributes 始终为空。我需要帮助找到更好的方法来实现这一目标。所以我最终可以得到结果数组,如上所示。任何帮助是极大的赞赏。
P.S:我已经尝试过条件回调和承诺,但我无法让它工作,因为我需要在每一步中传递参数。随时指出我错在哪里,或者如果有更好的方法来实现这一点,我很乐意学习。
【问题讨论】:
标签: javascript arrays node.js callback async.js