NodeJS Multiple Callback解决之使用Q Promises

在上一篇《Javascript Promises模式——相当酷的Callback Hell终结者》我们介绍了Javascript的Promise模式,接着我们就把Javascript Promise用到我们的代码中。

JavaScript Promise库 Q

之前试着用过Q,但是没有成功。或者说,在那时候不需要用上Q,所以没有深究。现在抱着学习的态度,重新试了一下,效果还不错。

A tool for making and composing asynchronous promises in JavaScript

Q是一个提供制作和创作异步Promise的JavaScript工具。Q 提供了一些辅助函数,可以将Node和其他环境适配为promise可用的。

转载保留: 《NodeJS Multiple Callback解决之使用Q Promises》

JavaScript Promise库 Q示例

官网给了一个简单的转换的说明

step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            step4(value3, function(value4) {
                // Do something with value4
            });
        });
    });
});

将他转换为

Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
    // Do something with value4
})
.catch(function (error) {
    // Handle any error from all above steps
})
.done();

但是,我们没有看懂,我们到底做了些什么。。

JavaScript Promise 库 Q实战

原生的代码是这样子的,用的是async库

async.parallel([
    function () {
        ‘use strict‘;
        pr.get(domain, next);
    },

    function () {
        ‘use strict‘;
        gs.get(name, next);
    },

    function () {
        ‘use strict‘;
        csdn.get(name, next);
    },

    function () {
        ‘use strict‘;
        zhihu.get(name, next);
    },

    function () {
        ‘use strict‘;
        alexa.get(domain, next);
    }
]);

但是总感觉写得有点乱,不过至少离开了所谓的回调大坑。

过程大致上就是当我们需要不断往我们的result里面添加东西。

于是将代码改成Promise的形式,接着就变成这样了

github.promise_get(response, name)
    .then(function (result) {
        return pr.promise_get(result, domain);
    })
    .then(function (result) {
        return csdn.promise_get(result, name);
    })
    .then(function (result) {
        return zhihu.promise_get(result, name);
    })
    .then(function (result) {
        return alexa.promise_get(result, domain);
    })
    .then(function (result) {
        callback(result);
    });

但是这样看上去写得有点不好,因为我们将过程固化在代码中,于是试着,用别的方法对其重构。

重构的第一步后就变成这样子

var info = Information.prototype;

info.pageRank_get = function(result){
    ‘use strict‘;
    return pageRank.promise_get(result, Information.prototype.domain);
};

info.alexa_get = function(result){
    ‘use strict‘;
    return alexa.promise_get(result, Information.prototype.domain);
};

info.csdn_get= function (result) {
    ‘use strict‘;
    return csdn.promise_get(result, info.name);
};

info.github_get= function (result) {
    ‘use strict‘;
    return github.promise_get(result, info.name);
};

info.zhihu_get = function (result) {
    ‘use strict‘;
    return zhihu.promise_get(result, info.name);
};

info.initVal = function (result) {
    ‘use strict‘;
    result = [];
    return result;
};

Information.prototype.get = function (callback) {
    ‘use strict‘;
    Q.fcall(info.initVal)
        .then(info.github_get)
        .then(info.csdn_get)
        .then(info.zhihu_get())
        .then(info.pageRank_get)
        .then(info.alexa_get)
        .then(function (result) {
            callback(result);
        });
};

先提出每一个方法,然后我们就可以选择我们需要用到的库。看上去比上面整洁多了,但是我们还需要下一步,以便继续。

时间: 2024-08-06 11:42:53

NodeJS Multiple Callback解决之使用Q Promises的相关文章

{Nodejs} 错误 HPE_INVALID_CONSTANT 解决

今天遇到 HPE_INVALID_CONSTANT 错误. 1. 再现 今天下午调用同事的接口, 莫名出现该异常.一直在找原因. 以下是http.get 代码.. 没发现问题,且该方法调用其他接口没问题. http.get(_options.url, function (res) { var pageData = ""; res.setEncoding(_options.encoding); res.on('error', function (err) { console.log(er

Host 'localhost' has multiple addresses. 解决办法

phpstorm调试php 错误提示: Host 'localhost' has multiple addresses. You must choose one explicitly!Couldn't create FastCGI listen socket on port localhost:35687 vi /etc/hosts 只保留127.0.0.1   localhost这一个关联项,其他的都注释掉. 127.0.0.1   localhost   #localhost.localdo

nodejs 回调地狱解决 promise async

nodejs毁掉地狱是一直被人诟病的,以下总结一下解决毁掉地狱的一些方法.(暂时研究的比较浅) 1.promise promise模式在任何时刻都处于以下三种状态之一:未完成(unfulfilled).已完成(resolved)和拒绝(rejected).以CommonJS Promise/A 标准为例,promise对象上的then方法负责添加针对已完成和拒绝状态下的处理函数.then方法会返回另一个promise对象,以便于形成promise管道,这种返回promise对象的方式能够支持开发

NodeJS设置Header解决跨域问题

app.all('*', function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header('Access-Control

nodejs内存溢出解决方法

解决方案一:通过 package.json 中的 "pro" 加大内存 解决方案二:使用 increase-memory-limit 插件,增加node服务器内存限制 "dependencies":{ "increase-memory-limit":"^1.6.0" } "script":{ "fix-memory-limit":"cross-env LIMIT=8000 in

野兽的Angular Api 学习、翻译及理解 - - $q 承诺与延迟

野兽的ng api学习 -- $q $q 一个帮助处理异步执行函数的服务.当他们做完处理时,使用它们的返回值(或异常). 受 Kris Kowa’s Q 的启发,这是一个实现promise/deferred对象的启用. $q的两种方式---这是一个更类似于Kris Kowal Q或jQuery的递延实现,另一种在一定程度上类似的ES6承诺. Deferred Api 一个被$q.defer()调用的deferred的新实例. deferred对象的目的是暴露相关承诺实例,以及APIs被执行的成功

Angular - - $q 承诺与延迟

$q 一个帮助处理异步执行函数的服务.当他们做完处理时,使用它们的返回值(或异常). 受 Kris Kowa’s Q 的启发,这是一个实现promise/deferred对象的启用. $q的两种方式---这是一个更类似于Kris Kowal Q或jQuery的递延实现,另一种在一定程度上类似的ES6承诺. Deferred Api 一个被$q.defer()调用的deferred的新实例. deferred对象的目的是暴露相关承诺实例,以及APIs被执行的成功或不成功情况,以及任务的状态. 方法

NodeJS优缺点及适用场景讨论

概述:NodeJS宣称其目标是“旨在提供一种简单的构建可伸缩网络程序的方法”,那么它的出现是为了解决什么问题呢,它有什么优缺点以及它适用于什么场景呢? 本文就个人使用经验对这些问题进行探讨. 一. NodeJS的特点 我们先来看看NodeJS官网上的介绍: Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.

[转载]NodeJS优缺点及适用场景讨论

http://www.xprogrammer.com/159.html 概述:NodeJS宣称其目标是“旨在提供一种简单的构建可伸缩网络程序的方法”,那么它的出现是为了解决什么问题呢,它有什么优缺点以及它适用于什么场景呢? 本文就个人使用经验对这些问题进行探讨. 一. NodeJS的特点 我们先来看看NodeJS官网上的介绍: Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast,