// synchronous Javascript
var result = db.get('select * from table1');
console.log('I am syncronous');
// asynchronous Javascript
db.get('select * from table1', function(result){
// do something with the result
});
console.log('I am asynchronous')
Run Code Online (Sandbox Code Playgroud)
我知道在同步代码中,console.log()在从db获取结果后执行,而在异步代码中,console.log()在db.get()获取结果之前执行.
现在我的问题是,异步代码的幕后执行是如何发生的,为什么它是非阻塞的?
我已经搜索了Ecmascript 5标准,以了解异步代码如何工作,但在整个标准中找不到异步这个词.
从nodebeginner.org我也发现我们不应该使用return语句,因为它阻止了事件循环.但是nodejs api和第三方模块在任何地方都包含return语句.那么什么时候应该使用return语句,何时不应该使用return语句?
有人可以对此有所了解吗?
找到了我的一些问题的答案,html5网络工作者!
虽然使用这个基本示例,如何将参数传递给Web worker?
worker.js的内容:
function doSomething() {
postMessage( ' done');
}
setTimeout ( "doSomething()", 3000 );
Run Code Online (Sandbox Code Playgroud)
js代码:
var worker = new Worker('worker.js');
worker.onmessage = function (event) {
alert(event.data);
};
Run Code Online (Sandbox Code Playgroud)