'How to use Async and await inside of a loop
I am using Firebase and Nodejs in order to calculate some values. There are 40+ JSON objects will be there in the variable 'data'. 'getOHLCofStock' function expects a value and it will return a promise. But what happens here is, that the console.log function gets executed without waiting for the promise to resolve. Therefore, I am getting 'undefined' in the console. Please help me to make this function wait and console the real value.
const path = db.ref(now);
path.on('value', async(snapshot) => {
for (const property in data) {
await zerodha.getOHLCofStock(property).then(async ohlc => {
console.log(ohlc);
//ohlc is 'undefined', but in fact, its not undefined. The 'await'
is not working here.
I want 'getOHLCofStock' should wait until the value gets resolved and
then only the console.log should execute.
})
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
