javascript - API 应为 %100 同步或 %100 异步示例

标签 javascript node.js asynchronous synchronous

我在学习https://nodejs.org/api/process.html#process_process_nexttick_callback_arg ,我被困在一个点上。我在下面引用它:

It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example:

// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!    
function maybeSync(arg, cb) {     
    if (arg) {      
        cb();       
        return;       
    }

    fs.stat('file', cb);

This API is hazardous because in the following case:

maybeSync(true, () => {       
     foo();     
});     
bar();   

It is not clear whether foo() or bar() will be called first.

我不明白为什么不清楚 foo() 还是 bar() 会先被调用。因为 arg 为真并且 maybeSync 函数同步工作。因此,一切都同步工作,我认为 foo() 将在 bar() 之前被调用。为什么这种情况并非如此?

The following approach is much better:

function definitelyAsync(arg, cb) {       
    if (arg) {      
        process.nextTick(cb);       
        return;
    }

    fs.stat('file', cb);    
}

最佳答案

执行不明确,因为 fs.stat() 是异步的并且最快在下一个 tick 时执行,这意味着 bar() 将始终在 foo 之前执行()

但是,通过引入 if (arg) 子句,其中 cb() 立即执行,那么 foo() 将在 bar() - 这是同步的。 因此,maybeSync() 在执行前不知道 arg 是什么,就没有可预测性。

definitelyAsync() 通过在 if (arg) 分支中安排对 cb() 的调用,强制始终异步执行,这将始终导致 bar()foo() 之前执行,而不管 arg 值如何。

关于javascript - API 应为 %100 同步或 %100 异步示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38158830/

相关文章:

javascript - 在 jquery mobile 中通过查询字符串传递变量

javascript - 无法反序列化完整字符串

javascript - 滚动到固定标题的 anchor 位置

javascript - 如何调试 Node.js 应用程序?

javascript - 找不到 Mongoose 模式

javascript - 奇怪的 $.post 行为

json - 将 http 响应从 Node 映射到 json 文件

javascript - 使用 $q 同步多个 Angular $http 调用/使用 $q.catch 进行错误处理

python - 如何从异步方法/线程传递/交换数据?

python - 通过回调传递数据