如何将异步节点函数转换为promise

时间:2013-10-21 20:01:22

标签: node.js 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"); });

我得到TypeError:无法调用未定义的方法'然后'。

此代码有什么问题?

2 个答案:

答案 0 :(得分:4)

Q中有various ways

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

// Work with rusable wrapper
var myAsyncPromiseFunction = Q.denodeify(myAsyncFunction);
myAsyncPromiseFunction(arg1, arg2);
<{3>}实施中的

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

一个显着的区别:由Deferred生成的Wrappers另外自动解析作为参数传递的promise,所以你可以这样做:

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

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

答案 1 :(得分:-2)

myAsyncFunction在您的代码中不返回任何内容(实际上未定义)。

如果你使用whenjs,通常的方式是这样的:

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;
};

现在你可以致电:

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