【问题标题】:Conditionally execute functions that have callbacks each returning values when triggered有条件地执行具有回调的函数,每个函数在触发时返回值
【发布时间】: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


    【解决方案1】:

    我认为promise list 可以完美地解决您的问题,只要您的结构正确。

    首先:让 fetchAttributes 返回一个承诺:

    return new Promise(function(resolve, reject) {
      ...Your try catch using resolve() and reject()
    })
    

    第二:创建你的承诺数组

    let fetchList= [];
    attributes.forEach((attr) => {
        fetchList.push(...your function)
    }
    

    第三:如果您不在乎是否失败,请确保添加反射,以便 promise.all() 始终完成 -> Check this stack post

    最后一旦你的 promise.all() 解析,你可以遍历所有返回的值并将它们推送到 newAttributes 变量!!!

    如果您遇到问题,我可以提供更多信息,但这应该可以帮助您开始!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2021-08-02
      • 2021-12-10
      相关资源
      最近更新 更多