[英]Javascript callback execution not working as per understanding
我试图理解以下回调:
doThis(andThenThis); function andThenThis() { console.log('and then this') } function doThis(callback) { setTimeout(function() { console.log('this first') }, 500) callback() }
我尝试使用回调,以便我的函数在setTimeout
之后执行,无论第一个函数需要多长时间来执行。
我希望它打印:'this first',然后是:'and then this'。 有什么办法可以做到吗?
您的代码执行以下操作:
... 500 毫秒后:
最大的错误是把应该先执行的代码放在了“延迟”的函数中!
这是正确执行 2 个日志的正确代码。
doThis(andThenThis)
function andThenThis() {
console.log('and then this')
}
function doThis(callback) {
console.log('this first') // this is executed immediately
setTimeout(function() {
callback() // this will be executed after 500ms
}, 500)
// console.log('this first') // if moved here it is still executed before the callback
}
如评论中所示,如果您切换操作 1 和 2,您仍然得到相同的结果,相同的日志顺序(以演示对 setTimeout() 的调用立即退出)。
简单的例子
function theCallBack(data){
console.log(data, "From doSomethingmethod")
}
function doSomething(callback){
//Calling callback after Some operation
//Example
axios.get(url)
.then(function(response){
callback(response)
})
}
doSomething(theCallBack);
这就是您使用回调函数的方式。
function doThis(callback) {
console.log('this first')
setTimeout(() => {
callback()
}, 500)
}
这个:
function doThis(callback) {
setTimeout(function() {
console.log('this first')
}, 500)
callback()
}
应该是这样的:
function doThis(callback) {
setTimeout(function() {
console.log('this first');
callback();
}, 500);
}
当它超出超时时间时,它会立即执行。 只有超时中的事情等待。 在这里试试:
doThis(andThenThis); function andThenThis() { console.log('and then this'); } function doThis(callback) { setTimeout(function() { console.log('this first'); callback(); }, 500); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.