Reputation: 786
How can I implement this code to run in correct order (A and B) without change the setTime using only callback?
function a() {
setTimeout(function () {
console.log('a');
},1000);
}
function b() {
console.log('b');
}
function c() {
a();
b();
}
c();
When run the c(), I need to run a() and b() in synchronous order, that's:
Upvotes: 0
Views: 52
Reputation: 219127
The asynchronous operation (what's being done in setTimeout()
) would need a callback to invoke when it's finished. Provide that callback to a()
:
function a(callback) {
setTimeout(function () {
console.log('a');
if (typeof callback === "function") {
callback();
}
},1000);
}
Then pass a reference to b
for that callback:
function c() {
a(b);
}
Upvotes: 1
Reputation: 150080
You mentioned using a callback - simply add an argument to a()
that is a callback function that you will call after doing the console.log(a)
, then when you call a()
pass a reference to b
:
function a(callback) {
setTimeout(function () {
console.log('a');
if (typeof callback === 'function')
callback();
},1000);
}
function b() {
console.log('b');
}
a(b); // note: no parentheses after b, i.e., a(b), *not* a(b())
a(); // note: a() still works without any argument
The test within a()
to check that callback
actually is a reference to a function means you can choose not to pass a callback and a()
will still work.
Upvotes: 3