回调访问数据

Callback access data

本文关键字:数据 访问 回调      更新时间:2023-09-26

我创建了一个小函数,它检查我提交给它的标签列表,并将好的放在好的数组中,坏的放在坏的数组中。

这一切都是在回调中完成的,所以一旦回调完成,我的其余代码就可以继续了

我对如何从回调访问原始函数中的数据有点困惑。

function findTags() {
    validateTags(tags, function () {
        //How do I access the bad array here?
        console.log('These tags are bad ' + badArray.join(','))
    });
}
//This will validate the tags submitted and strip out anything bad from them.
//We will return either success if everything is good or an array of the bad tags to fix.
function validateTags(tags, callback) {
    var badArray = new Array(),
        goodArray = new Array();
    tags = tags.split(',');
    for (var i = 0; i < tags.length; i++) {
        //If the tag contains just alphanumeric, add it to the final array.
        if (tags[i].match(/^[a-z0-9's]+$/i)) {
            goodArray.push(tags[i]);
        } else {
            //Since we didnt match an alphanumeric, add it to the bad array.
            badArray.push(tags[i]);
        }
    }
    //console.log(badArray);
    //console.log(goodArray);
    if (callback) {
        callback(badArray);
    }
}

简单。只需在回调定义中使用一个参数-

validateTags(tags, function (badArray) {
    //How do I access the bad array here?
    console.log('These tags are bad ' + badArray.join(','))
});

在验证标记定义中,将badArray作为参数传递给callback调用。因此,只需为回调定义定义一个参数,它就会捕获数组作为其值。