var back = fn(); // fn 是一个异步方法, 不用yield的情况下
console.log('我不执行'); //怎么确保这行不执行,在外层不想用generator
就像 fs.readFile() 和fs.readFileSync()的效果一样,很想知道后者的同步方法是怎么实现的? 有源码看吗
简而言之:同步方法是通过函数体内部循环达到结果的,异步方法是通过thread pool 委托事件循环实现的。
你可以参考一下链接:
https://github.com/nodejs/node/blob/master/src/node_file.cc
同步方法的关键code 贴给你。
#define POST
do {
if (cb != NULL) {
uv__work_submit(loop, &req->work_req, uv__fs_work, uv__fs_done);
return 0;
}
else {
uv__fs_work(&req->work_req);
return req->result;
}
}
while (0)
static void uv__fs_work(struct uv__work* w) { int retry_on_eintr; uv_fs_t* req; ssize_t r;
req = container_of(w, uv_fs_t, work_req); retry_on_eintr = !(req->fs_type == UV_FS_CLOSE);
do { errno = 0;
#define X(type, action)
case UV_FS_ ## type:
r = action;
break;
switch (req->fs_type) {
X(ACCESS, access(req->path, req->flags));
X(CHMOD, chmod(req->path, req->mode));
X(CHOWN, chown(req->path, req->uid, req->gid));
X(CLOSE, close(req->file));
X(FCHMOD, fchmod(req->file, req->mode));
X(FCHOWN, fchown(req->file, req->uid, req->gid));
X(FDATASYNC, uv__fs_fdatasync(req));
X(FSTAT, uv__fs_fstat(req->file, &req->statbuf));
X(FSYNC, fsync(req->file));
X(FTRUNCATE, ftruncate(req->file, req->off));
X(FUTIME, uv__fs_futime(req));
X(LSTAT, uv__fs_lstat(req->path, &req->statbuf));
X(LINK, link(req->path, req->new_path));
X(MKDIR, mkdir(req->path, req->mode));
X(MKDTEMP, uv__fs_mkdtemp(req));
X(OPEN, uv__fs_open(req));
X(READ, uv__fs_buf_iter(req, uv__fs_read));
X(SCANDIR, uv__fs_scandir(req));
X(READLINK, uv__fs_readlink(req));
X(REALPATH, uv__fs_realpath(req));
X(RENAME, rename(req->path, req->new_path));
X(RMDIR, rmdir(req->path));
X(SENDFILE, uv__fs_sendfile(req));
X(STAT, uv__fs_stat(req->path, &req->statbuf));
X(SYMLINK, symlink(req->path, req->new_path));
X(UNLINK, unlink(req->path));
X(UTIME, uv__fs_utime(req));
X(WRITE, uv__fs_buf_iter(req, uv__fs_write));
default: abort();
}
#undef X } while (r == -1 && errno == EINTR && retry_on_eintr);
if (r == -1) req->result = -errno; else req->result = r;
if (r == 0 && (req->fs_type == UV_FS_STAT || req->fs_type == UV_FS_FSTAT || req->fs_type == UV_FS_LSTAT)) { req->ptr = &req->statbuf; } }
var back;
fn(function callback(result){back=result;})
while(back==null){}
console.log('我不执行');
如楼上@qimenxiaozi 所说 XDDDDDDDD