Correct way to write loops for promise.

后端 未结 13 1721
猫巷女王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:43

    I'd make something like this:

    var request = []
    while(count<10){
       request.push(db.getUser(email).then(function(res) { return res; }));
       count++
    };
    
    Promise.all(request).then((dataAll)=>{
      for (var i = 0; i < dataAll.length; i++) {
    
          logger.log(dataAll[i]); 
      }  
    });
    

    in this way, dataAll is an ordered array of all element to log. And log operation will perform when all promises are done.

    0 讨论(0)
  • 2020-11-22 15:47

    There is a new way to solve this and it's by using async/await.

    async function myFunction() {
      while(/* my condition */) {
        const res = await db.getUser(email);
        logger.log(res);
      }
    }
    
    myFunction().then(() => {
      /* do other stuff */
    })
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://ponyfoo.com/articles/understanding-javascript-async-await

    0 讨论(0)
  • 2020-11-22 15:50

    First take array of promises(promise array) and after resolve these promise array using Promise.all(promisearray).

    var arry=['raju','ram','abdul','kruthika'];
    
    var promiseArry=[];
    for(var i=0;i<arry.length;i++) {
      promiseArry.push(dbFechFun(arry[i]));
    }
    
    Promise.all(promiseArry)
      .then((result) => {
        console.log(result);
      })
      .catch((error) => {
         console.log(error);
      });
    
    function dbFetchFun(name) {
      // we need to return a  promise
      return db.find({name:name}); // any db operation we can write hear
    }
    
    0 讨论(0)
  • 2020-11-22 15:50

    Use async and await (es6):

    function taskAsync(paramets){
     return new Promise((reslove,reject)=>{
     //your logic after reslove(respoce) or reject(error)
    })
    }
    
    async function fName(){
    let arry=['list of items'];
      for(var i=0;i<arry.length;i++){
       let result=await(taskAsync('parameters'));
    }
    
    }
    
    0 讨论(0)
  • 2020-11-22 15:50
    function promiseLoop(promiseFunc, paramsGetter, conditionChecker, eachFunc, delay) {
        function callNext() {
            return promiseFunc.apply(null, paramsGetter())
                .then(eachFunc)
        }
    
        function loop(promise, fn) {
            if (delay) {
                return new Promise(function(resolve) {
                    setTimeout(function() {
                        resolve();
                    }, delay);
                })
                    .then(function() {
                        return promise
                            .then(fn)
                            .then(function(condition) {
                                if (!condition) {
                                    return true;
                                }
                                return loop(callNext(), fn)
                            })
                    });
            }
            return promise
                .then(fn)
                .then(function(condition) {
                    if (!condition) {
                        return true;
                    }
                    return loop(callNext(), fn)
                })
        }
    
        return loop(callNext(), conditionChecker);
    }
    
    
    function makeRequest(param) {
        return new Promise(function(resolve, reject) {
            var req = https.request(function(res) {
                var data = '';
                res.on('data', function (chunk) {
                    data += chunk;
                });
                res.on('end', function () {
                    resolve(data);
                });
            });
            req.on('error', function(e) {
                reject(e);
            });
            req.write(param);
            req.end();
        })
    }
    
    function getSomething() {
        var param = 0;
    
        var limit = 10;
    
        var results = [];
    
        function paramGetter() {
            return [param];
        }
        function conditionChecker() {
            return param <= limit;
        }
        function callback(result) {
            results.push(result);
            param++;
        }
    
        return promiseLoop(makeRequest, paramGetter, conditionChecker, callback)
            .then(function() {
                return results;
            });
    }
    
    getSomething().then(function(res) {
        console.log('results', res);
    }).catch(function(err) {
        console.log('some error along the way', err);
    });
    
    0 讨论(0)
  • 2020-11-22 15:50

    Here's another method (ES6 w/std Promise). Uses lodash/underscore type exit criteria (return === false). Note that you could easily add an exitIf() method in options to run in doOne().

    const whilePromise = (fnReturningPromise,options = {}) => { 
        // loop until fnReturningPromise() === false
        // options.delay - setTimeout ms (set to 0 for 1 tick to make non-blocking)
        return new Promise((resolve,reject) => {
            const doOne = () => {
                fnReturningPromise()
                .then((...args) => {
                    if (args.length && args[0] === false) {
                        resolve(...args);
                    } else {
                        iterate();
                    }
                })
            };
            const iterate = () => {
                if (options.delay !== undefined) {
                    setTimeout(doOne,options.delay);
                } else {
                    doOne();
                }
            }
            Promise.resolve()
            .then(iterate)
            .catch(reject)
        })
    };
    
    0 讨论(0)
提交回复
热议问题