function one(){
console.log(1);
}
function two(callback){
setTimeout(()=>{
console.log(2);
},2000);
callback();
}
two(one);
function one(){
console.log(1);
}
function two(callback){
setTimeout(()=>{
console.log(2);
},2000);
callback();
}
two(one);
While I am running this code, 1 is displaying first and then 2 because 2 is taking 2 second time to display. Suppose if there is an api instead of console.log(2) in function two which is taking 2 second to respond, so How I can call function one after pletion of function two using callback(); which I can do in this case if I use callback() inside setTimeout function but what if there is an api where I am not using setTimeout and it's taking 2-3 second?
Share Improve this question edited Jan 31, 2020 at 13:52 GrafiCode 3,3743 gold badges29 silver badges32 bronze badges asked Jan 31, 2020 at 10:55 AyazAyaz 411 silver badge4 bronze badges 3-
You can call api with
async
-await
, so that 2nd function will be called after api call is pleted :) – Akhil Aravind Commented Jan 31, 2020 at 10:57 - I want to call 2nd function first which is taking longer time then function 1 using callback. Is that possible? – Ayaz Commented Jan 31, 2020 at 11:02
-
call your
second function
first withasync
and then call thefirst function
on pletingsecond
. Simple. Bro think simple it will resolve all questions – Akhil Aravind Commented Jan 31, 2020 at 11:05
4 Answers
Reset to default 4Even if there is an api
call which takes time to resolve, you can still use a callback at the same way you just did with the setTimeout
example.
Alternatively, use a Promise
:
function two(callback) {
new Promise(res => {
setTimeout(() => {
res();
}, 2000);
}).then(callback)
}
or using async/await
syntax:
async function two(callback) {
await new Promise(res => {
setTimeout(() => {
res();
}, 2000);
})
callback();
}
you can use sync function like this
function two() {//this function takes 2 seconds
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
function one(){
console.log("one");
}
async function asyncCall() {
console.log('calling');
const result = await two();
one()
// expected output: 'resolved'
}
asyncCall();
here is reference link
You can use Promises:
function one(){
console.log(1);
}
function two(){
return new Promise((resolve, reject) => {
setTimeout(()=>{
console.log(2);
resolve()
},2000);
})
}
two().then(() => one())
Put callback();
inside setTimeout
:
function one(){
console.log(1);
}
function two(callback){
setTimeout(()=>{
console.log(2);
callback();
},2000);
}
two(one);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744966309a4603699.html
评论列表(0条)