0

I expected the code to output: QQ d QQ e QQ f ["a","b","c","d","e","f"] but is doesn't the out put is not in sequence i want, I would like test() to wait in the middle of loop when it do test2() and get the answer the print out QQ and the item in t2, how can I resolve it?

$('#sr').click(function() {
  test();
});
var test = function test() {
  var t1 = ["a", "b", "c"];
  var t2 = ["d", "e", "f"];
  t2.forEach(function(item, index) {
    console.log(test2("QQ"));
    console.log(item);
    t1.push(item);
  });
  console.log(t1);
}

var test2 = function test2(x) {
  setTimeout(function() {
    return x;
  }, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input value="show result" type="button" id="sr" />

6
  • Where do you think does return x; return to? console.log(test2("QQ")); will log undefined because test2 doesn’t return anything. Commented Oct 1, 2021 at 18:39
  • 2
    i don't think he was asking for delay, he probably wants to know about promises and async await Commented Oct 1, 2021 at 18:44
  • This questions about JS promises is likely a better fit for the duplicate. Commented Oct 1, 2021 at 18:47
  • @Ki “I would like test() to wait in the middle of loop when it do test2()”. Also, the linked post has several answers with different approaches: asyncawait, Promises, setTimeout, for loops, etc. Commented Oct 1, 2021 at 18:47
  • setTimeout would be a really bad way to handle what the OP is trying to do. The OP may not realize that. Commented Oct 1, 2021 at 18:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.