【问题标题】:How to actually use Q promise in node.js?如何在 node.js 中实际使用 Q Promise?
【发布时间】:2014-05-05 21:28:54
【问题描述】:

这可能是一个菜鸟问题,但我是新来的承诺,并试图弄清楚如何在 node.js 中使用Q

我看到tutorial

开头
promiseMeSomething()
    .then(function (value) {}, function (reason) {});

但我无法理解.then 的确切来源。我猜它来自

var outputPromise = getInputPromise()
    .then(function (input) {}, function (reason) {});

但是getInputPromise() 来自哪里?我发现以前没有提到它。


我已经将它包含在我的项目中

var Q = require('q');

// this is suppose, the async function I want to use promise for
function async(cb) {
    setTimeout(function () {
        cb();
    }, 5000);
}

async(function () {
    console.log('async called back');
});

在我的示例中如何使用Q 及其.then

【问题讨论】:

标签: javascript node.js promise q


【解决方案1】:

promiseMeSomething()会返回一个Q promise对象,里面会有then函数,也就是defined,像这样

Promise.prototype.then = function (fulfilled, rejected, progressed) {

创建 Promise 对象的最简单方法是使用 Q 函数构造函数,如下所示

new Q(value)

将创建一个新的 Promise 对象。然后,您可以像这样附加成功和失败处理程序

new Q(value)
.then(function(/*Success handler*/){}, function(/*Failure handler*/){})

此外,如果您将单个 nodejs 样式的函数传递给 .then 函数,它将以这样的成功值调用该函数

callback(null, value)

或者如果有问题,那么

callback(error)

对于您的特定情况,setTimeout 接受要调用的函数作为第一个参数。因此,只需要几行代码就可以让它真正与 Promise 一起工作。所以,Q有一个方便的功能,为此,Q.delay,可以这样使用

var Q = require('q');

function async() {
    return Q.delay(1000)
}

async()
.then(function() {
    console.log('async called back');
});

你可以这样写更短

Q.delay(1000)
    .then(function() {
        console.log('async called back');
    });

如果你想用其他值调用回调函数,那么你可以这样做

Q.delay(1000, "Success")
    .then(function(value) {
        console.log('async called back with', value);
    });

当您希望在两个函数之间有延迟并且第二个函数依赖于第一个函数时,这将很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多