One Promise for Multiple Promises - Concurrency Is

2019-07-25 03:33发布

In the method "myMethod" of my "gulpfile.js" I want to create multiple Promises. The quantity depends on the array size (method parameter). When I call the method I want to make sure that all promises are fulfilled before I continue. I would prefer to return not before all promises are fulfilled.

Please have a look at the last five lines of code.

Dependencies

var promiseAll = require('gulp-all');
var del = require('del');
var deleteEmpty = require('delete-empty');

gulp-all | del | delete-empty

Helper Method

var oneForAllPromises = function(promises){
    var promAll = promiseAll(promises);
    promAll.then(function(param) {
        console.log('foo');
    }, function(err) {
        console.error('foo');
    });
    return promAll;
}

Problematic Code

var myMethod = function(array1, array2){
    var promise = del(array1, {force: true});
    promise.then(paths => {console.log('foo');});

    var promises = [];
    promise.then(()=>{
        for(var i=0; i<array2.length; i++){
            promises[i] = new Promise(function(resolve, reject) {
                deleteEmpty(array2[i], {force: true},
                    function(err, deleted){
                        if(err){
                            console.log('foo');
                            reject
                        }else{
                            console.log('foo');
                            resolve
                        }
                    }
                );
            });
        }
    });

    // PROBLEM: Returns empty promises array
    console.log("promiesesLENGTH: "+promises.length); // promiesesLENGTH: 0

    // Create one promise for all the promises
    return oneForAllPromises(promises);
}

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-25 03:42

At the time of the console.log, the first promise promise = del(array1, {force: true}); is not yet finished, so none of the code in the then is yet executed. That's why your promises are empty.

You can simply return in a then another promise:

var myMethod = function(array1, array2){
    var promise = del(array1, {force: true});

    return promise.then(() => {
        return Promise.all(array2.map(array2value => {
            return new Promise(function(resolve, reject) {
                deleteEmpty(array2value, {force: true}, (err, deleted) => {
                    if (err) {
                        reject(err);
                    } else{
                        resolve()
                    }
                });
            });
        }
    });
}
查看更多
登录 后发表回答