reza
reza

Reputation: 6358

how to turn an async node function to a promise

I have this async function that I want to turn into a promise

    var myAsyncFunction = function(err, result) {
        if (err) 
            console.log("We got an error");


        console.log("Success");
    };

    myAsyncFunction().then(function () { console.log("promise is working"); });

and I get TypeError: Cannot call method 'then' of undefined.

What is wrong with this code?

Upvotes: 2

Views: 2886

Answers (2)

Mariusz Nowak
Mariusz Nowak

Reputation: 32838

There are various ways in Q:

Q.nfcall(myAsyncFunction, arg1, arg2);
Q.nfapply(myAsyncFunction, [arg1, arg2]);

// Work with rusable wrapper
var myAsyncPromiseFunction = Q.denodeify(myAsyncFunction);
myAsyncPromiseFunction(arg1, arg2);

in Deferred implementation:

var myAsyncPromiseFunction = deferred.promisify(myAsyncFunction);
myAsyncPromiseFunction(arg1, arg2);

One notable difference: Wrappers as generated by Deferred additionally auto-resolve promises passed as an arguments, so you can do:

var readFile = deferred.promisify(fs.readFile);
var writeFile = deferred.promisify(fs.writeFile);

// Copy file
writeFile('filename.copy.txt', readFile('filename.txt'));

Upvotes: 4

Andrew
Andrew

Reputation: 5340

myAsyncFunction return nothing(undefined actually) in your code.

If you use whenjs, the normal way will be like this:

var myAsyncFunction = function() {

    var d = when.defer();

    //!!!do something to get the err and result

    if (err) 
       d.reject(err);
    else
       d.resolve.(result);

    //return a promise, so you can call .then
    return d.promise;
};

Now you can call:

myAsyncFunction().then(function(result(){}, function(err){});

Upvotes: -2

Related Questions