javascript: 同步编程的最佳方式是什么

javascript: what is the best way to do synchronous programming

使用 Javascript 进行同步编程的最佳方法是什么?

JavaScript运行时是单线程环境——也就是说,它一次执行一个命令(同步)。但是,承载 JavaScript 运行时的浏览器在多线程环境(操作系统)中运行。这意味着虽然 JavaScript 运行时一次只能处理一行代码,但浏览器可以在此期间做其他事情。

所以,要进行同步编程,您不需要做任何特别的事情。只写代码。但是,如果该代码要求浏览器做一些工作(通过许多 Web API 中的任何一个,例如 AJAX 请求、地理定位请求、setTimeout() 等.),浏览器将从 JavaScript 运行时异步执行这些操作。在这些情况下,您将需要为异步操作何时完成设置一个回调函数 - 您无法知道何时完成,但您可以为它何时完成做好准备。

这是不涉及 Web API(同步)调用的代码示例:

var x = "First";
console.log(x); 

var y = "Third";
var z = "Second";

function test(){
  console.log(z); 
}

console.log(y);  

test();

// This code will be run synchronously. The output will be:
"First"
"Third"
"Second"

现在,我们将介绍 Web API 调用 (setTimeout()),它是在 JavaScript 运行时之外处理的。这个例子清楚地表明了 JS 运行时不能同时做两件事。

console.log("...starting...");


// Note that the timer is passed 0, which would seem to indicate that it should run the 
// passed function immediately, but that won't happen because the JS runtime MUST complete
// the synchronous processing of the current execution context and go into an idle state
// before any new code can be executed
setTimeout(function(){ 
  console.log("Message from setTimeout()...COMPLETE");
}, 0); // <-- NOTE THE ZERO (AS IN RUN RIGHT NOW)

// This message will be shown before the setTimeout message because the JS runtime
// cannot do two things at once. It MUST finish this code block first.
console.log("...working...");


// Result:  "...starting...", "...working...", "Message from setTimeout()...COMPLETE"