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" />
Eric
  • 89
  • 1
  • 1
  • 5
  • Where do you think does `return x;` return _to_? `console.log(test2("QQ"));` will log `undefined` because `test2` doesn’t return anything. – Sebastian Simon Oct 01 '21 at 18:39
  • 2
    i don't think he was asking for delay, he probably wants to know about promises and async await – K i Oct 01 '21 at 18:44
  • [This questions about JS promises](https://stackoverflow.com/questions/28921127/how-to-wait-for-a-javascript-promise-to-resolve-before-resuming-function) is likely a better fit for the duplicate. – devlin carnate Oct 01 '21 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: `async`–`await`, Promises, `setTimeout`, `for` loops, etc. – Sebastian Simon Oct 01 '21 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. – devlin carnate Oct 01 '21 at 18:48
  • i believe this is what you want `var test2 = function test2(x) { return new Promise((resolve) => setTimeout(() => resolve(x), 1000)) } var test = async function test() { var t1 = ["a", "b", "c"] var t2 = ["d", "e", "f"] t2.forEach(async function (item, index) { console.log(await test2("QQ")) console.log(item) t1.push(item) if (index + 1 == t2.length) { console.log(t1) } }) }` sorry it's a mess – K i Oct 01 '21 at 18:59

0 Answers0