API should be either %100 synchronous or %100 asynchronous example

感情迁移 提交于 2020-01-03 19:17:34

问题


While i'm studying https://nodejs.org/api/process.html#process_process_nexttick_callback_arg , i'm stucked at a point. I'm quoting it below :

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.

I didn't understand why it is not clear whether foo() or bar() will be called first. Because arg is true and maybeSync function works synchronously. Thus everything works synchronously and foo() will be called before bar(), i think. Why this is not true for this case?

The following approach is much better:

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

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

回答1:


Execution is not clear because fs.stat() is async and executes at soonest on next tick, meaning that bar() will always execute before foo().

However, by introducing the if (arg) clause where cb() is executed immediately, then foo() will execute before bar() - this is in sync. Thus, maybeSync() has no predictability without knowing what arg is, before execution.

The definitelyAsync() forces always async execution, by scheduling a call to cb() inside the if (arg) branch, which will always result in bar() being executed before foo() regardless of the arg value.



来源:https://stackoverflow.com/questions/38158830/api-should-be-either-100-synchronous-or-100-asynchronous-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!