问题描述
我在这里真的很挣扎,无法掌握编写异步 JavaScript 的方法.你能否提供一个简单的 JavaScript 函数的例子,它是用纯 JavaScript 异步编写的(而不是使用 Node.js 或 JQuery)
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 本身是同步和单线程的.您不能编写异步函数;纯 JS 没有计时 API.并行线程不会有副作用.
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.
您可以做的是使用您的环境(Node.js、Webbrowser)提供的一些 API,这些 API 允许您安排异步任务 - 使用超时、ajax、FileAPI、requestAnimationFrame
、nextTick
、WebWorkers、DOM 事件等等.
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.
使用 setTimeout
的示例(由HTML 计时 API):
window.setTimeout(function() {
console.log("World");
}, 1000);
console.log("Hello");
更新:从 ES6 开始,promise 作为异步原语内置到纯 JavaScript 中,所以你可以这样做
Update: Since ES6 there are promises as an asynchronous primitive built into plain JavaScript, so you can do
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.
这篇关于什么是异步 javascript 函数的简单示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!