Search code examples
javascriptjsonnode.jspromisebluebird

Bluebird Promises and JSON.parse on an Array


I want to have access on a JSONARRAY in a JSONOBJECT. But after the Bluebird Promises, i can not JSON.parse on the Entrys of the "arrayOfResults". If i would do this, the code is in a deadlock. The database is redis. Please help :)

UPDATE: the code after that part caused the deadlock, sorry :(

var JSONOBJECT = {
 "A":DATA, 
 JSONARRAY :[{A:x}, {B:C}]
};

db.set(SOMEID, JSON.stringify(JSONOBJECT));



function somefunction(ArrayOfIDS){
		var promises = [];
		for (var i = 0; i < ArrayOfIDS.length; i++) {
			promises.push(db.getAsync(ArrayOfIDS[i]));
	        }
		return Promise.all(promises).then(function(arrayOfResults) {
			for (i = 0; i < arrayOfResults.length; i++) {
				//THIS IS NOT WORKING, but i need to parse it back to JsonObject
				//var JSONOBJECT = JSON.parse(arrayOfResults[i]);
                
                //The JSONOBJECT below only contains the string of the JSONOBJECT
				var JSONOBJECT = arrayOfResults[i];
                //So this line below is not working
                                var JSONARRAY = JSONOBJECT.JSONARRAY;
			}
			//SOME MORE CODE
			return SOMETHING;
		});
};


Solution

  • arrayOfResults contains promise results, not values, so you cant apply sync methods like JSON.parse

    try this function

    function somefunction(ArrayOfIDS) {
        return Promise.map(ArrayOfIDS, function(ID, index){
            return Promise.resolve()
                .then(function(){
                    return db.getAsync(ID);
                })
                .then(function(JSONOBJECT) {
                    return {
                        obj: JSON.parse(JSONOBJECT),
                        index: index
                    }
                })
        })
        .then(function(ARRAYOFJSONOBJECTS){
            return SOMETHING;
        });
    }