knex promises - how to wait while two funcions finish their work

How to add code that will run only when both processes are completed?

normalise1();
normalise2();

function normalise1() {
    return knex("ingredients")
        .select("name", "id")
        .map(function (ingredient) {            
            var normalised_name = common.normalise(ingredient.name);
            knex('ingredients').where('id', ingredient.id).update({ name_normalised: normalised_name }).then();
        });
};

function normalise2() {
    return knex("synonyms")
        .select("synon_name as name", "id")
        .map(function (ingredient) {            
            var normalised_name = common.normalise(ingredient.name);
            knex('synonyms').where('id', ingredient.id).update({ synon_name_normalised: normalised_name }).then();
        });
};

I tried something like in different ways

Promise.all([normalise1(), normalise2()])
    .then(() => console.log('Done'));

but it didn't work. Basically console.log('Done') appears before all process is done. I believe that this is because of missing Promise part inside functions, but I cannot figure out exactly how.

1 answer

  • answered 2018-01-13 17:39 guest271314

    The functions are not called when passed to Promise.all(), no Promise is returned from .map().

    Call the functions and return knex() from .map() call, which may also require using Promise.all() within the function calls.