javascript - 如何在 node.js 中实际使用 Q Promise?

标签 javascript node.js promise q

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

我看到 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

最佳答案

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

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

关于javascript - 如何在 node.js 中实际使用 Q Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678613/

相关文章:

javascript - 无法修改和测试 fork 的 GitHub 库 - npm 错误!找不到版本

javascript - 在 promise 链中等待 DOM 元素中的突变

javascript - 带有 promise.prototype.finally 的 Axios 不起作用

javascript - 正则表达式:如何替换以 "w/"和 "h"开头的四位数字?

javascript - JavaScript Image 对象如何与浏览器缓存交互?

node.js - 如何将 STDOUT 从生成的子进程传输到日志文件中并同时将其打印到控制台?

Node.js 服务器使用负载均衡器发送事件

mysql - Req.File.Path 未定义

javascript - 等待所有响应,然后调用函数

javascript - 使用 select2、json 请求和 Laravel 的动态下拉菜单