【问题标题】:how to turn an async node function to a promise如何将异步节点功能转变为承诺
【发布时间】: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 之间的基本区别所在。

标签: node.js promise


【解决方案1】:

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

Deferred 实现中:

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

一个显着的区别:由 Deferred 生成的包装器还自动解析作为参数传递的承诺,因此您可以这样做:

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

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

【讨论】:

    【解决方案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){});
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2018-09-26
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    相关资源
    最近更新 更多