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" />