用q.js链接承诺 [英] chaining promises with q.js

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

问题描述

我正在试图理解承诺链是如何工作的。我正在使用 q.js 。这是我正在玩的东西。

I'm trying to understand how promise chaining works. I'm using q.js. Here's what I'm playing with.

var Q = require("q"); // npm install q

// the function Q(value) returns a fulfilled promise with the value... I think.
Q(1).then(Q(2)).then(Q(3)).then(Q(4)).then(function(n) {
    console.log(n);
});

Q(1).then(function(n) {
    return Q(2);
}).then(function(n) {
    return Q(3);
}).then(function(n) {
    return Q(4);
}).then(function(n) {
    console.log("done: " + n);
});

我的问题基本归结为为什么第一个日志 1 而后者记录了我的预期,基本上记录了1到4.我原本希望第一个记录 4 而不是 1

My question basically boils down to why does the first one log 1 while the latter one logs what I would expect and basically logs 1 through 4. I had hoped the first one would log 4 instead of 1.

我真的只是希望能够有一些返回承诺的方法,然后像时尚一样将它们链接在一起 - 我想我可以使用 async 和瀑布,但只是想知道这是否可以通过promises实现。

I really just wanted to be able to have some methods that return promises and then chain them together in a waterfall like fashion - I guess I could use async and waterfall, but just wanted to know if this could be achieved w/ promises.

推荐答案

这是因为然后并不期望另一个承诺作为参数。相反,它需要处理程序函数回调和/或 errback ,前者是您在第二个示例中传递的。 确实,任何函数的参数都会被忽略

It's because then doesn't expect another promise as an argument. Rather it expects handler functions, an callback and/or an errback, the former you are passing in your 2nd example. Indeed any argument that is not a function is simply ignored.

来自文档


如果在处理程序中返回一个值,则outputPromise将会完成。

If you return a value in a handler, outputPromise will get fulfilled.

如果你抛出处理程序中的异常,outputPromise将被拒绝。

If you throw an exception in a handler, outputPromise will get rejected.

如果在处理程序中返回一个promise,则outputPromise将成为该promise。能够成为新承诺对于管理延迟,结合结果或从错误中恢复是有用的。

If you return a promise in a handler, outputPromise will "become" that promise. Being able to become a new promise is useful for managing delays, combining results, or recovering from errors.

所以是的,链接承诺可以完成。你在第二个例子中正确地做到了这一点。

So yes, chaining promises can be done. You're doing it right in your 2nd example.

这里通过实现承诺的人为设计的例子可能会让链接承诺的工作看起来过于冗长,但实际上却是如此世界用法,你通常链接承诺,因为你对他们的返回值感兴趣,例如:

It's possible that the contrived example here of passing fulfilled promises makes the way chaining promises works seem overly verbose, but in real world usage, you typically chain promises because you're interested in their return values, e.g.:

somethingAsync().then(function (n) {
  return somethingElseAsync(n);
})
.then(function (n) {
  return somethingElseAsync(n);
})
.then(function (result) {
  // ...
})

(实际上这个镜像 async.waterfall 。如果你只是想按顺序调用一系列异步函数而不考虑他们的结果你可以使用 async.series

(Actually this mirrors async.waterfall. If you just wanted to call a series of async functions in order with no regards to their results you could use async.series)

这篇关于用q.js链接承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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