在Parse Cloud代码中未复制数组

时间:2015-11-02 08:23:31

标签: javascript arrays parse-platform

我在Parse Cloud Code中复制数组时遇到问题。在下面的findAllAssociatedBrands函数中,我使用Parse Queries来获取成功回调的数组。在成功回调时,日志语句:console.log(JSON.stringify(brandList [i]));打印数组元素,然后我复制新数组中的所有元素。在for循环之后,log语句将新数组显示为[],并且其中没有元素。我错过了什么?

function findAllAssociatedBrands(beaconObj) {

var typeOfBeacon = beaconObj.get("type");
var beaconBrandRelation = beaconObj.relation("brand");
var query = beaconBrandRelation.query();
var listOfAllBeaconAssociatedBrands = [];

query.find({
    success: function(brandList) {
        for (var i = 0; i < brandList.length; i++) {
            console.log(JSON.stringify(brandList[i]));
            listOfAllBeaconAssociatedBrands[i] = brandList[i];
        }

        console.log(listOfAllBeaconAssociatedBrands);
    },
    error: function(error) {
        console.log("Beacon Brand Relation Error: " + error.code + "  " + error.message);
    }
});

return listOfAllBeaconAssociatedBrands;
 }

1 个答案:

答案 0 :(得分:0)

query.find()是一个异步函数,所以findAllAssociatedBrands()函数的最后一行在query.find()之后立即执行,所以query.find()通常甚至没有足够的时间来运行成功回调所以你必须绑“return listOfAllBeaconAssociatedBrands;”到成功回调结束。

function findAllAssociatedBrands(beaconObj) {

var typeOfBeacon = beaconObj.get("type");
var beaconBrandRelation = beaconObj.relation("brand");
var query = beaconBrandRelation.query();
var listOfAllBeaconAssociatedBrands = [];

query.find({
    success: function(brandList) {
        for (var i = 0; i < brandList.length; i++) {
            console.log(JSON.stringify(brandList[i]));
            listOfAllBeaconAssociatedBrands[i] = brandList[i];
        }

        console.log(listOfAllBeaconAssociatedBrands);
return listOfAllBeaconAssociatedBrands;
    },
    error: function(error) {
        console.log("Beacon Brand Relation Error: " + error.code + "  " + error.message);
    }
});


 }