Correct way to write loops for promise.

后端 未结 13 1857
猫巷女王i
猫巷女王i 2020-11-22 15:20

How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iterat

13条回答
  •  执念已碎
    2020-11-22 15:42

    I don't think it guarantees the order of calling logger.log(res);

    Actually, it does. That statement is executed before the resolve call.

    Any suggestions?

    Lots. The most important is your use of the create-promise-manually antipattern - just do only

    promiseWhile(…, function() {
        return db.getUser(email)
                 .then(function(res) { 
                     logger.log(res); 
                     count++;
                 });
    })…
    

    Second, that while function could be simplified a lot:

    var promiseWhile = Promise.method(function(condition, action) {
        if (!condition()) return;
        return action().then(promiseWhile.bind(null, condition, action));
    });
    

    Third, I would not use a while loop (with a closure variable) but a for loop:

    var promiseFor = Promise.method(function(condition, action, value) {
        if (!condition(value)) return value;
        return action(value).then(promiseFor.bind(null, condition, action));
    });
    
    promiseFor(function(count) {
        return count < 10;
    }, function(count) {
        return db.getUser(email)
                 .then(function(res) { 
                     logger.log(res); 
                     return ++count;
                 });
    }, 0).then(console.log.bind(console, 'all done'));
    

提交回复
热议问题