2013-10-21 44 views
2

有,我想变成一个承诺我如何把一个异步节点功能的承诺

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


     console.log("Success"); 
    }; 

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

,我得到这个类型错误异步功能:不能调用方法“那么”的定义。

这段代码有什么问题?

+0

我使用q表示我的诺言包 – reza

+0

你的函数没有返回什么,你想做什么 – Esailija

+0

你的函数看起来不是非常异步,但更像是一个异步函数的回调。你打给谁? – Bergi

回答

4

various ways在问:

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

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

Deferred实现:

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

一个显着的区别:包装器由作为参数传递递延还自动解析承诺产生的,所以你可以做:

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

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

myAsyncFunction ret在你的代码中没有任何东西(实际上未定义)。

如果使用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){}); 
+2

你的代码看起来就是在执行[deferred anti-pattern](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) – Esailija