Thursday, 13 April 2017

Wait for a function to finish before firing the next in Node JS

I've got this gulp task:

// default task, runs through all primary tasks
gulp.task("default", ["media", "scripts", "styles", "html"], function () {
    // notify that task is complete
    gulp.src("gulpfile.js")
        .pipe(plugins.gulpif(ran_tasks.length, plugins.notify({title: "Success!", message: ran_tasks.length + " task" + (ran_tasks.length > 1 ? "s" : "") + " complete! [" + ran_tasks.join(", ") + "]", onLast: true})));

    // trigger FTP task if FTP flag is passed
    if (plugins.argv.ftp) {
        config_module.config(gulp, plugins, settings);
        ftp_module.upload(gulp, plugins, settings, ran_tasks, on_error);
    }

    // reset ran_tasks array
    ran_tasks.length = 0;
});

Which works great, except for the FTP bit. I need config_module.config() to finish before ftp_module.upload() can be triggered. I've tried setting up promises and anonymous functions with callbacks, but neither of those solutions worked; the FTP function keeps firing before config.

How can I make the ftp_module.upload() function wait for config_module.config() to finish before firing?


EDIT: Here's the promise I tried, which still doesn't work correctly:

new Promise(function (resolve) {
    config_module.config(gulp, plugins, settings);
    resolve();
}).then(function () {
    ftp_module.upload(gulp, plugins, settings, ran_tasks, on_error);
});



via JacobTheDev

No comments:

Post a Comment