I am trying to apply callbacks in javascript, this is a sample code analogous to a piece of code something in my website built in node.js
var a = function(obj,callback){
var p = {name: 'name', age: 35}
obj.p = p
setTimeout(function(){
console.log("waiting for three seconds");
}, 3000);
console.log("...................")
callback(obj)
}
var b = function(obj){
var q = {name: 'name2', age: 37}
obj.q = q
console.log("*******************")
}
var func = function(){
var obj = {};
a(obj,b)
console.log(obj)
}
func()
on running this code i get the output: -
...................
*******************
{ p: { name: 'name', age: 35 }, q: { name: 'name2', age: 37 } }
waiting for three seconds
Now here, in the function "a" the line "waiting for three seconds" is printed after 3 seconds in that time the callback function is also called, hence the line "waiting for three seconds" is printed after the output of function "b" ie is "****************"
However i want the output to be this
waiting for three seconds
...................
*******************
{ p: { name: 'name', age: 35 }, q: { name: 'name2', age: 37 } }
How can i achieve this? kindly help i am stuck here.
You can use make use of JavaScript promises to achieve the synchronisation. Change your code like below.
We have wrapped up all the async operations inside promise. await will hold on the execution until the promise is resolved.
var a = async function(obj) {
var p = {name: 'name', age: 35}
obj.p = p
await timeout( 3000)
console.log("...................")
b(obj)
}
var b = function(obj) {
var q = {name: 'name2', age: 37}
obj.q = q
console.log("*******************")
}
function timeout(ms) {
return new Promise(resolve =>
setTimeout(function(){
console.log("waiting for three
seconds");
resolve()
}, ms));
}
var func = async function(){
var obj = {};
await a(obj,b)
console.log(obj)
}
func()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.