我已经读过为什么我必须使用await来异步运行方法。如果我不想等待方法完成再继续怎么办?和回调总是异步的吗?并且仍在尝试了解回调实际上是异步的。
例如,doThat
将需要等待GET
数据才能对其进行任何处理。如上面的第二个链接所述,javascript是单线程的。
doThis(doThat);
function doThis(callback) {
$.get('http://some_api/some_resource', function (data) {
callback(data);
});
};
function doThat(data) {
// Do something with data
};
我所见过的唯一真正的异步功能是使用诺言和多个诺言,例如,我可以在动画包装时加载其他数据。我想帮助您更好地了解传统回调实际上是异步的。具体的例子会有所帮助。
例如,我可以在动画结束时加载其他数据。
这正是您可以使用代码执行的操作。请注意,在等待doThat
执行时,您可以运行其他代码(实际上,“运行其他代码”会让人们感到困惑)。就像您的动画示例一样:
function doThis(callback) {
$.get('http://some_api/some_resource', function (data) {
callback(data);
});
};
function doThat(function (data) {
// Do something with data
});
function doAnotherThing(function (data) {
// Do something with data
});
doThis(doThat);
// without waiting for doThat to run, you can IMMEDIATELY call:
doThis(doAnotherThing);
// without waiting for either doThat or doAnotherThing you
// can output some pretty animations:
setInterval(do_animation,100);
// and without waiting for any of the above you can do anything else:
document.body.innerHTML += 'hello';
请注意,令大多数人感到困惑的是,该document.body.innerHTML='hello'
部分在其上方的任何代码之前都已运行。这意味着回调是异步的,因为它们是在数据到达时执行的,而不是在调用函数时执行的。
请注意,并非所有的回调都是异步的。例如,Array.prototype.forEach()
是同步的:
document.body.innerHTML += 'before<br>';
['hello','world'].forEach(function(x){
document.body.innerHTML += x;
})
document.body.innerHTML += '<br>after';
决定回调是异步还是同步的是调用它的函数。另请参阅:我知道回调函数是异步运行的,但是为什么呢?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句