node.js - [nodejs] 为什么文件的 api 有同步的,但是数据库操作几乎都是异步的?
巴扎黑
巴扎黑 2017-04-17 15:28:14
0
2
488

nodejs 里面 fs 模块提供了 readFile 和 readFileSync 同步和异步的 api

而 mysql 库里面的 query 都是同步的,而没有 querySync 之类的方法

数据库的读写和文件的 IO 有什么区别?是做不了还是只是保持异步的风格?

谢谢~

巴扎黑
巴扎黑

reply all(2)
PHPzhong

Thank you for the invitation. The synchronization interfaces of node are for the convenience of developers and are provided natively.

Several other database interfaces are third-party modules implemented by other author organizations.

Under normal circumstances, it is recommended to write asynchronously. Of course, there will be various callbacks that are not elegant. At this time, it is recommended to use the various synchronization methods provided by the native to optimize the code and achieve elegance.

For example: Generator / Promise / Async and other native solutions.

Or mainstream asynchronous processing solutions encapsulated with co etc.

迷茫

There is actually no difference in the process, but readFile is a native API, and the official provides this kind of synchronous call.
And query is the api provided by the node-mysql module, which does not provide users with such methods.

Actually, you can implement one yourself. It just so happens that node v7+ can support async and await.
Something like this:

querySync(sql, data) {
    return new Promise((resolve, reject) => {
        connection.query(sql, data, (err, result) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(result);
        });
    });
}

async getData(sql, data) {
    const data = await querySync(sql, data)
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template