我有一个异步函数,我想把它变成一个 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: Cannot call method 'then' of undefined.
这段代码有什么问题?
最佳答案
有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);
一个显着的区别:由 Deferred 生成的包装器另外自动解析作为参数传递的 promise ,因此您可以执行以下操作:
var readFile = deferred.promisify(fs.readFile);
var writeFile = deferred.promisify(fs.writeFile);
// Copy file
writeFile('filename.copy.txt', readFile('filename.txt'));
关于node.js - 如何将异步 Node 函数转变为 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19503612/