Search code examples
javascriptnode.jsknex.js

Loop value can not work inside knex in node js


I tried to get loop values inside knex function but I got final value of a loop.

for (i = 0; i < 10; i++) {

    knex_in.raw(query).then(function (result) {
                    console.log(i)
    });

    }

Need help.


Solution

  • The counter in your loop (i) is a global variable. On each iteration of your loop, you are creating a promise. By the time your promises have resolved, the loop is complete, therefore i is the final value.

    The solution is to save the value of i in a scoped variable. This can be done in a few ways, here are two:

    You can use let (depending on ES6 support)

    for (let i = 0; i < 10; i++) {
    
      setTimeout(function() {
        console.log(i);
      }, 500);
    
    }

    Or you could store the value of i in a scoped variable by creating a function:

    function someFunction(value) {
      setTimeout(function() {
        console.log(value);
      }, 500);
    }
    
    for (i = 0; i < 10; i++) {
      someFunction(i)
    }