Home > Mobile >  How i can call function inside function
How i can call function inside function

Time:11-25

I would like to call a function that is inside another function, that function will clear the timeout.

I have tried the following code, but without success:

async function Blast2() {
  const delayTime = 1000;
  const timer = (ms) => new Promise((res) => setTimeout(res, ms));

  function ClearDelayTime() {
    return clearTimeout(blast);
  }

  const blast = setTimeout(function () {
    let blast =
      "SELECT * FROM admin_contacts,temporary WHERE blast_status = 'sended'";
    db.query(blast, async function (err, result, field) {
      if (err) throw err;

      loop: {
        for (var i = 0; i < result.length; i  ) {
          console.log(result[i].telefone);
          await timer(delayTime); // then the created Promise can be awaited
        }
      }
    });
  }, delayTime);
}

// I Want Call the function ClearDelayTime() inside Blast2()
Blast2().ClearDelayTime();

CodePudding user response:

I've refactored your code. It now immediately returns a function that can be used to abort.

const db = {
  query: (sql, callback) => callback(undefined,
    [{telefone:1},{telefone:2},{telefone:3},{telefone:4},{telefone:5}])
}

function blast2() {

  const delayTime = 1000
  const timer = ms => new Promise(res => setTimeout(res, ms))

  let sql = "SELECT * FROM admin_contacts,temporary WHERE blast_status = 'sended'";

  let abort = false;

  db.query(sql, (err, result) => {
    if (!err) {
      (async () => {
        for(let i=0; i<result.length && !abort; i  ) {
          console.log(result[i].telefone);
          await timer(delayTime);
        }
      })();
    }
  })

  return () => abort = true;

}
let abortFunc = blast2();
setTimeout(abortFunc, 2500);

CodePudding user response:

Your function Blast2 doesn't return anything. If you want to call a function inside it, you could return and store it using a variable, then call it.

Something like this:

const f1 = () => {
  console.log('f1 called')
  const f2 = () => {
    console.log('f2 called')
  }
  
  return f2
}

const returnedFunction = f1()

console.log(returnedFunction())

  • Related