Promise, promise, change the function to support both callback and promise

Time:2021-6-22

BeginnersNode.js, withExpressdevelopmentWebProject.
And it’s not a small project. It’s very risky.

It was relatively simple at the beginning and didn’t use itPromiseIt’s going well,
With the deepening of development, it is not necessary toPromiseIt’s too late.

So there is a problem that some of the previously written methods are not supportedPromise
If you change it directly toPromiseBefore that, we have to change the places we called, and the workload is a bit heavy.
If you add onePromiseIt’s a bit wordy and ugly, as follows:

//That is to say, write two versions of the same function
function getInfo(uid, callback) { ... };
function getInfoPromise(uid) { ... };

hearBluebirdThere is onepromisifyMethod, you can put the methodPromiseIt’s not easy,
However, I feel that loading one more library for this method is a bit of a waste of memory,
after allNode.jsNow there’s native supportPromiseIt’s too late,
Can I change the function to “manual”CallbackCallback and supportPromiseWhat about it?
The following modifications have been made:

//Originally, only callback version was supported
var getInfo = function(uid, callback) {
    var sql = "select * from v_user where uid=? limit 1";
    Mysql.query(sql, [uid], function(err, row) {
        if(err) return callback(err);
        if(row.length===0) return callback();

        var info = row[0];
        callback(null, info);
    });
};
//After modification, it supports both callback and promise
var getInfo = function(uid, callback) {
    return new Promise(function(resolve, reject) {
        if (callback) {
            resolve = function (ret) {
                callback(null, ret);
            };
            reject = callback;
        }

        var sql = "select * from v_user where uid=? limit 1";
        Mysql.query(sql, [uid], function(err, row) {
            if(err) return reject(err);
            if(row.length===0) return resolve();

            var info = row[0];
            resolve(info);
        });
    });
};

But I don’t know if this writing method is smart enough. I welcome your advice.

Recommended Today

What is “hybrid cloud”?

In this paper, we define the concept of “hybrid cloud”, explain four different cloud deployment models of hybrid cloud, and deeply analyze the industrial trend of hybrid cloud through a series of data and charts. 01 introduction Hybrid cloud is a computing environment that integrates multiple platforms and data centers. Generally speaking, hybrid cloud is […]