Search code examples
javascriptnode.jsdiscord.jsreplit

JS, how to get promises in loops


I just recently started working with js and still can't figure out the promises in loops. I am working with repl.it db. Let's say I have an array that contains keys and I would like to query each element of the array to put the values into a another array.

Something like this (of course, this code doesn't work):

var arr = ['key1','key2','key3'];
var newarr = ['name1','name2','name3'];

for (var i = 0; i < arr.length; i++) {
   db.get(arr[i]).then(val=> {
   newarr[i] = { name: newarr[i], value: val };
   });
};

console.log(newarr) // [ { name: name1, value: value1 },{ name: name2, value: value2 },{ name: name3, value: value3 } ]

Solution

  • you can try wrapping the for loop in an async function and add await before db.get

    like this:

    const getData = async () => {
        try {
            for (var i = 0; i < arr.length; i++) {
                await db.get(arr[i]).then(val => {
                    newarr[i] = { name: newarr[i], value: val };
                });
            };
        } catch (err) {
            console.log('err:', err)  //handle errors
        }
        console.log(newarr)
    }
    
    getData() // run it