Hello there I am getting the desired result when am using promise but how should I implement it with callback when am returning something from the function.
result with promise
JavaScript
x
32
32
1
2
const first = () => {
3
return ("I am first");
4
}
5
6
const second = () => {
7
return new Promise((resolve,reject) => {
8
setTimeout(()=>{
9
resolve("I am second");
10
},1000);
11
})
12
}
13
14
const third = () => {
15
return("I am third");
16
}
17
18
//using promise
19
20
const solve = async () => {
21
var f = first();
22
console.log(f);
23
24
var ans = await second();
25
console.log(ans);
26
27
var t = third();
28
console.log(t);
29
}
30
31
solve();
32
*** using callback ***
JavaScript
1
30
30
1
const first = () => {
2
return "I am first";
3
}
4
5
var temp;
6
const second = (cb) => {
7
setTimeout(function() {
8
return "I am second";
9
temp = cb();
10
}, 1000);
11
}
12
13
const third = () => {
14
return "I am third";
15
}
16
17
18
const solve = () => {
19
var f = first();
20
console.log(f);
21
22
var s = second(third);
23
setTimeout(()=>{
24
console.log(s);
25
console.log(temp);
26
},1100)
27
}
28
29
solve();
30
OUTPUT should be
I am first
I am second
I am third
Advertisement
Answer
You don’t need that global temp
variable, and your setTimeout
callback in second
doesn’t really work. It should be cb("I am second");
, just like where you’d usually call resolve("I am second");
in a new Promise
. Then you can receive that value as the parameter of the callback function you’re passing to second(…)
, which should then log it and continue with the remaining steps of the script.
JavaScript
1
28
28
1
const first = () => {
2
return "I am first";
3
}
4
5
const second = (cb) => {
6
setTimeout(function() {
7
cb("I am second");
8
}, 1000);
9
}
10
11
const third = () => {
12
return "I am third";
13
}
14
15
16
const solve = () => {
17
var f = first();
18
console.log(f);
19
20
second((s) => {
21
console.log(s);
22
23
const t = third();
24
console.log(t);
25
});
26
}
27
28
solve();
Notice this is not unlike your promise version if you were to use .then()
instead of async
/await
syntax:
JavaScript
1
12
12
1
const solve = () => {
2
var f = first();
3
console.log(f);
4
5
second().then((s) => {
6
console.log(s);
7
8
var t = third();
9
console.log(t);
10
});
11
}
12