Q.js-使用延迟 [英] Q.js - Using deferred

查看:68
本文介绍了Q.js-使用延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从下面的示例中获取文本的值?

How do I get the value of the text from the example below?

Q.js有一个使用Deferred的示例:

Q.js has an example on using Deferred:

var deferred = Q.defer();
FS.readFile("foo.txt", "utf-8", function (error, text) {
    if (error) {
        deferred.reject(new Error(error));
    } else {
        deferred.resolve(text);
    }
});
return deferred.promise;

在这种情况下,使用了节点异步功能。我要做的是从被返回的deferred.promise中获取文本的值。当我console.log(deferred.promise)时,我得到以下信息:

In this case, there is a node async function being used. What I want to do is get the value of text from the deferred.promise being returned. When I console.log(deferred.promise) I get this:

{ promiseSend: [Function], valueOf: [Function] }

我在做什么错了(因为我只是从此处复制/粘贴示例: https://github.com/kriskowal/q#using-deferreds )或我还需要什么可以从文件中实际获取文本?

What am I doing wrong (as I just copy/pasted the example from here: https://github.com/kriskowal/q#using-deferreds) or what else do I need to do to actually get that text from the file?

我知道node.js具有上述调用的同步版本-我的目标是了解递延的工作原理

I am aware that node.js has a synchronous version of the call above - my goal is to understand how deferred works with this library.

推荐答案

您可以通过 .then()方法

You can get the value via the .then() method of a Promise:

function read() {
    // your snippet here...
}

read().then(function (text) {
    console.log(text);
});

此外,错误处理程序可以作为第二个参数传递给。 ()或使用 .fail()方法:

Also, error handlers can be passed either as a 2nd argument to .then() or with the .fail() method:

read().fail(function (err) {
    console.log(err);
});

这篇关于Q.js-使用延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆