Idiomatic prerequisite processing with ES6 Promises

I am new to ES6 Promises and doing research. I have some code running in NodeJS that does some async work, but I have a few preconditions that need to be checked first. I am looking for an idiomatic best practice to solve this problem (if such a thing exists) along with some reasoning. I hope to get an understanding, as I already have working code.

Consider the following fictional fragment:

function doStuff(data, cb) {
     if (!data) {
         return cb(new Error("Don't be an idiot"));
     }

     externalLibrary.doSomethingCallbackAsync(data, cb);
}

If I translated this to the land of promises, I see two options.


Option 1 , I can include the precondition in the promise.

function doStuff(data){
    return new Promise((resolve, reject) => {
        if (!data) {
            return reject(new Error("Don't be an idiot"));
        }

        externalLibrary.doSomethingCallbackAsync(data, function(err, newData) {
            if (err) {
                return reject(err);
            }
            return resolve(newData);
        });
    });
}

2, . , Promise.reject(), , , , .

function doStuff(data){
    if (!data) {
        return Promise.reject(new Error("Don't be an idiot"));
    }

    return new Promise((resolve, reject) => {
        externalLibrary.doSomethingCallbackAsync(data, function(err, newData) {
            if (err) {
                return reject(err);
            }
            return resolve(newData);
        });
    });
}

2 , Promise.reject(), , 2 . , .

+4
1

, Promise.reject(), , ,

. . , .

2 , API, promises (, return externalLibrary.doSomethingAsync(data)) Promise antipattern.

+3

All Articles