0

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 } ]
Makasin
  • 5
  • 1
  • 2
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – evolutionxbox May 24 '21 at 01:32

1 Answers1

0

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
Peter
  • 32
  • 2
  • 3
    This code would be better if you didn't mix `await` and `.then()`. Just use `await`. Also, it won't work as shown because the value of `i` will be wrong due to the asynchronous nature of `.then()`. Use `let` instead of `var` for the loop variable. – jfriend00 May 24 '21 at 01:56