如何将一个asynchronous节点function变成一个承诺
我有这个asynchronousfunction,我想变成一个承诺
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:不能调用未定义的方法。
这段代码有什么问题?
问:有多种方式 :
Q.nfcall(myAsyncFunction, arg1, arg2); Q.nfapply(myAsyncFunction, [arg1, arg2]); // Work with rusable wrapper var myAsyncPromiseFunction = Q.denodeify(myAsyncFunction); myAsyncPromiseFunction(arg1, arg2);
在延期实施中:
var myAsyncPromiseFunction = deferred.promisify(myAsyncFunction); myAsyncPromiseFunction(arg1, arg2);
一个显着的区别是:由Deferred生成的包装器自动parsing作为parameter passing的promise,所以你可以这样做:
var readFile = deferred.promisify(fs.readFile); var writeFile = deferred.promisify(fs.writeFile); // Copy file writeFile('filename.copy.txt', readFile('filename.txt'));
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){});