Wednesday, 31 May 2017

Call functions in bluebird's then

How can I call a function inside of a then()? I am new to Bluebird and previously I would simply trigger the callback to inform that the called function is done with it's stuff.

Here is my "main code" which inserts locale data into my Mongo and Redis database.

var promise = Language.findOne({}).exec()

promise.then(function(languages) {
    /* If collection is empty initialize it */
    if(!languages)
        return insertLanguagesIntoMongoDB()
})
.then(function() {
    /* Make sure it's cached in Redis */
    return insertLanguagesIntoRedis()
})
.catch(function(err) {
    throw err
})

This is how my function looks like, but it says "callback is not a function":

function insertLanguagesIntoRedis(callback) {
    logger.info("Inserting languages into redis db")
    var promise = Language.find({}).exec()
    promise.then(function(languages) {
        if(!languages)
            throw new Error("Couldn't find any languages in MongoDB's Language collection")

        var languageJson = []
        for(var i=0; i<languages.length; i++) {
            var object = {}
            object.id = languages[i].iso_code
            object.text = languages[i].name_en
            languageJson.push(object)
        }
        redis.set('languages', JSON.stringify(languageJson))
        return callback()
    })
    .catch(function (err) {
        throw err
    })
}

So how would I properly define and call my insertLanguagesIntoRedis and insertLanguagesIntoMongoDB functions?



via kentor

No comments:

Post a Comment