javascript - 使用 q.js 链接 promise

标签 javascript promise q

我正在尝试了解 promise 链的工作原理。我正在使用 q.js .这就是我正在玩的东西。

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

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

最佳答案

这是因为 then 不期望另一个 promise 作为参数。相反,它需要处理程序函数、一个回调 和/或一个errback,这是您在第二个示例中传递的前者。 Indeed any argument that is not a function is simply ignored .

From the docs :

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

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

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.

所以是的,可以实现链接 promise 。您在第二个示例中做对了。

这里传递已实现的 promise 的人为示例可能使链接 promise 的工作方式看起来过于冗长,但在现实世界的使用中,您通常会链接 promise ,因为您对它们的返回值感兴趣,例如:

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

(实际上 this 反射(reflect)了 async.waterfall。如果你只是想按顺序调用一系列异步函数而不考虑它们的结果,你可以使用 异步系列)

关于javascript - 使用 q.js 链接 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074685/

相关文章:

javascript - 使用固定列垂直滚动

javascript - YouTube 异步函数

javascript - AngularJS 函数未定义

javascript - 如何在 Promise.all 中访问已解决的 Promise es6

database - 如何使用nodejs pg-promise库将带有uuid数组的记录插入到pg表中

javascript - 在 promise 数组上使用 'all' 聚合函数时的最终处理程序

javascript - 如何显示/隐藏网格中的所有列?

javascript - promise Stripe API

javascript - Q - 链接同步 promise 来处理成功和失败

javascript - 链接多个可选异步 Ajax 请求