Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for the for loop to complete and then return the value

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'])
       }
 }
like image 481
Karthik Avatar asked Oct 26 '25 18:10

Karthik


2 Answers

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)

like image 108
codemonkey Avatar answered Oct 29 '25 09:10

codemonkey


Process transform async to sync in javascript we have 3 ways, include:

  • Use callback function https://www.w3schools.com/js/js_callback.asp
  • Use Promise, you create return the function is Promise and then you can call Promise.then() to coding more next step after done Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
  • Use Async/Await https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

If you want I can help you how to process your code, please show more detail. Tks

like image 22
xuan hung Nguyen Avatar answered Oct 29 '25 07:10

xuan hung Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!