【发布时间】:2013-10-23 02:36:27
【问题描述】:
我有这个异步函数,我想把它变成一个承诺
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.
这段代码有什么问题?
【问题讨论】:
-
我正在使用 q 作为我的承诺包
-
你的函数没有返回任何东西,你在做什么
-
你的函数看起来不是很异步,但更像是一个异步函数的回调。你打电话给哪个?
-
我正在尝试理解/学习如何使用 Promise 来避免回调地狱。所以为了理解这个概念,我写了这个示例代码。我认为这将是一个简单的例子;回调模板...这就是示例背后的动机。由于我没有 myAsyncFunction 的返回值,即使我将代码更改为 function(err),我仍然会收到 TypeError: Cannot call method 'then' of undefined
-
如果你只是给我们一个回调的模板,我们只能给你一个如何处理promise的模板:
.then(console.log.bind(console, "Success"), console.log.bind(console, "We got an error"))。但是如何使用那个回调或者promise方法,你首先需要一个异步的函数。这就是callback style and promises 之间的基本区别所在。