I'm trying to iterate through a value('test') and sent it to a class function and push the returned value into an array('t'). How can I wait for the for loop to finish and then print the array('t')?
I tried using Promises and function wrapper but to no use. Here is the code snippet:
t = []
test = ['1', '2']
for(var i in test) {
console.log('inside for loop')
new myFile.class(mysqlParams).myfunc(2, test[i], result=> {
t.push(result)
})
console.log('t: ' + t)
}
Can someone please help me?
Edit:
myfunc(num, test, callback) {
connectToMysqlDatabase()
connection.query(getTestcaseContentCommand, function(err, testContent) {
if (err) {
console.log(err)
}
else {
result(testContent[0]['testcaseContent'])
}
}
Here is how to rewrite your specific code to accomplish what you're trying to accomplish:
const callbackFunc = (param1, param2, callback) => {
setTimeout(() => callback('Ok'), 1000)
}
let t = []
const test = ['1', '2'];
const promises = [];
for(let i in test) {
promises.push(new Promise(resolve => {
callbackFunc(2, test[i], result => {
resolve(result)
})
}))
}
Promise.all(promises)
.then(result => {
t = result;
console.log(t);
})
Note, that in your case, had myfunc returned a promise instead of a callback, it'd be a bit simpler, but since that's not the case, you need to populate an array with promises and then resolve them all using Promise.all
I would also point out that if your code is iteself inside an async function, you could resolve Promise.all like so: const t = await Promise.all(promises)
Process transform async to sync in javascript we have 3 ways, include:
If you want I can help you how to process your code, please show more detail. Tks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With