什么是异步 javascript 函数的简单示例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13806695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a simple example of an asynchronous javascript function?
提问by Jasdeep Khalsa
I am really struggling here to get to grips with writing asynchronous JavaScript. Could you please provide an example of a simple JavaScript function which is asynchronous written in plain JavaScript (and not using Node.js or JQuery)
我在这里真的很努力来掌握编写异步 JavaScript。你能否提供一个简单的 JavaScript 函数的例子,它是用纯 JavaScript 异步编写的(而不是使用 Node.js 或 JQuery)
回答by Bergi
JavaScript itself is synchronous and single-threaded. You cannot write an asynchronous function; plain JS has no timing API. There will be no side-effects from parallel threads.
JavaScript 本身是同步的和单线程的。您不能编写异步函数;纯 JS 没有计时 API。并行线程不会有副作用。
What you can do is use some APIs provided by your environment (Node.js, Webbrowser) that allow you to schedule asynchronous tasks - using timeouts, ajax, FileAPI, requestAnimationFrame, nextTick, WebWorkers, DOM events, whatever.
你可以做的是使用你的环境(Node.js的,的Webbrowser),允许您安排异步任务提供了一些API -使用超时,AJAX功能,FileAPI, requestAnimationFrame,nextTick,WebWorkers,DOM事件,等等。
An example using setTimeout(provided by the HTML Timing API):
使用示例setTimeout(由HTML Timing API 提供):
window.setTimeout(function() {
console.log("World");
}, 1000);
console.log("Hello");
Update: Since ES6 there are promises as an asynchronous primitive built into plain JavaScript, so you can do
更新:由于 ES6 有承诺作为内置于纯 JavaScript 中的异步原语,所以你可以这样做
Promise.resolve("World").then(console.log); // then callbacks are always asynchronous
console.log("Hello");
However, on their own they're not really helpful when there is nothing you could wait for (such as a timeout). And they don't change anything about the threading model either, all execution is run-to-completion without any events interfering midway.
但是,就其本身而言,当您无法等待(例如超时)时,它们并没有真正的帮助。而且它们也不会改变线程模型的任何内容,所有执行都是从运行到完成,没有任何事件干扰中途。
回答by Peter Rasmussen
This is asynchronous:
这是异步的:
setTimeout(function(){
console.log('1');
}, 2000);
console.log('2');
2 will be written to the console before 1. Because setTimeout is async.
2 会在 1 之前写入控制台。因为 setTimeout 是异步的。
回答by raina77ow
Here's one very simple example:
这是一个非常简单的例子:
for (var i = 0; i < 10; i++) {
window.setTimeout(function() {
console.log(i);
}, 2000);
}
You might expect these console.log()calls to show you 0, 1, 2etc., as in this snippet:
您可能希望这些console.log()调用向您展示0, 1, 2等等,如以下代码段所示:
for (var i = 0; i < 10; i++) {
console.log(i);
}
But in fact only 10s will be printed! The reason that functions passed into setTimeoutfunction (as its 'callback' argument) will be invoked afterforloop is completed - i.e., after ivalue is set to 10.
但实际上只会10打印 s!函数传入setTimeout函数的原因(作为它的“回调”参数)将在for循环完成后被调用- 即在ivalue 设置为 10 之后。
Yet you should understood one thing: all JavaScript in a browser executes on a single thread; asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution queue. Here's a brilliant articlewritten by John Resig on this topic.
但是你应该明白一件事:浏览器中的所有 JavaScript 都在单个线程上执行;异步事件(例如鼠标单击和计时器)仅在执行队列中有空缺时才运行。这是John Resig 撰写的关于此主题的精彩文章。

