Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.all().then() - then() executes before all() completed

In a gulp task I have the following code that creates an array of gitAction promises that get executed within a Promise.all() statement. Afterwards, I'm calling a further statement in a then(). But the then() is being called before the git pulls in the all() have terminated. Any clues please?

var git = require('gulp-git');
var gitActionPromise = function(repo, url) {
    console.log('git action '+repo);
    var pathToRepo = './repos/'+repo;

    if (fs.lstatSync(pathToRepo).isDirectory()) {
        return new Promise((resolve, reject) => {
            git.pull('origin', 'master', {cwd: pathToRepo}, function (err) {
                console.log(repo + " pull done!");
                if (err) {
                    console.log('error');
                    reject(err);
                } else {
                    console.log('ok');
                    resolve();
                }
            })
        })
    } else {
        return new Promise((resolve, reject) => {
            git.clone(url, {cwd: pathToRepo}, function (err) {
                console.log(repo + " clone done!");
                if (err) {
                    console.log('error');
                    reject(err);
                } else {
                    console.log('ok');
                    resolve();
                }
            })
        })
    }
};

var repos = package.repos || {};
var promises = Object.keys(repos).map(function(repo) {
    return gitActionPromise(repo, repos[repo]);
});

Promise.all(promises).then(
    console.log('something else')   <= this line was causing my issue
);                                     needed to be enclosed in function
like image 245
ianbeks Avatar asked Dec 02 '15 15:12

ianbeks


1 Answers

You have to pass a function to then:

Promise.all(promises).then(function() {
    console.log('something else');
});

The code you have simply logs "something else" right away.

like image 60
Joseph Silber Avatar answered Oct 01 '22 12:10

Joseph Silber