首页 > 代码库 > Q的深层嵌套

Q的深层嵌套

1.如果将异步方法用同步的方式执行,try catch能捕获到错误,同时不会阻塞到主进程,因此console.log(3333)能执行.

var fs = require(‘fs‘);

try { 

   var data = http://www.mamicode.com/fs.readFileSync(‘sample.txt‘, ‘utf-8‘);

   console.log(data);

} catch (err) { 

// 出错了   

console.log(err);}console.log(3333);



2.对于某些库不带回调函数,但是又是异步方法,这就很难捕捉错误了var d = domain.create();

d.name = ‘d1‘;

process.on(‘uncaughtException‘, function (err) {
console.log(‘Caught exception: ‘ + err);
});


d.on(‘error‘,function(err){
console.log(‘domain捕获到错误‘,err);
});

d.run(function() {
console.log(1);
var fs = require(‘fs‘);
fs.readFile(‘sample.txt‘, ‘utf-8‘);
console.log(2);
}
);

console.log(3);
结果:异步的方法,如果没有回调函数就会在运行完之后抛出错误,其后续的程序都会执行,而用domain捕获的同步方法,则会将进程阻塞,后续方法不会执行

1
2
3
domain捕获到错误 { [Error: ENOENT: no such file or directory, open ‘sample.txt‘]
errno: -2,
code: ‘ENOENT‘,
syscall: ‘open‘,
path: ‘sample.txt‘,
domain:
Domain {
domain: null,
_events: { error: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
members: [],
name: ‘d1‘ },
domainThrown: true }


var d = domain.create();
d.name = ‘d1‘;

process.on(‘uncaughtException‘, function (err) {
console.log(‘Caught exception: ‘ + err);
});


d.on(‘error‘,function(err){
console.log(‘domain捕获到错误‘,err);
});

d.run(function() {
console.log(1);
var fs = require(‘fs‘);
fs.readFileSync(‘sample.txt‘, ‘utf-8‘);
console.log(2);
}
);

console.log(3333);
结果:同步的方法用domain,一旦有错误就会阻塞进程.

1
domain捕获到错误 { [Error: ENOENT: no such file or directory, open ‘sample.txt‘]
errno: -2,
code: ‘ENOENT‘,
syscall: ‘open‘,
path: ‘sample.txt‘,
domain:
Domain {
domain: null,
_events: { error: [Function] },
_eventsCount: 1,
_maxListeners: undefined,
members: [],
name: ‘d1‘ },
domainThrown: true }

Process finished with exit code 0





Q的深层嵌套