你如何正确地从承诺中返回多个值? [英] How do you properly return multiple values from a promise?

查看:150
本文介绍了你如何正确地从承诺中返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到过几次某种情况,我不知道如何妥善解决。假设以下代码:

I've recently run into a certain situation a couple of times, which I didn't know how to solve properly. Assume the following code:

somethingAsync()
  .then( afterSomething )
  .then( afterSomethingElse )

function afterSomething( amazingData ) {
  return processAsync( amazingData );
}
function afterSomethingElse( processedData ) {
}

现在可能会出现这样的情况:我希望在之后访问 amazingData afterSomethingElse

Now a situation might arise where I would want to have access to amazingData in afterSomethingElse.

一个明显的解决方案是从 afterSomething 返回一个数组或一个哈希,因为,你只能从一个函数返回一个值。但是我想知道是否有办法让 afterSomethingElse 接受2个参数并同样调用它,因为这似乎更容易记录和理解。

One obvious solution would be to return an array or a hash from afterSomething, because, well, you can only return one value from a function. But I'm wondering if there is way to have afterSomethingElse accept 2 parameters and invoke it likewise, as that seems a lot easier to document and understand.

我只是想知道这种可能性,因为有 Q.spread ,这与我想要的东西类似。

I'm only wondering about this possibility since there is Q.spread, which does something similar to what I want.

推荐答案

您无法解决具有多个属性的承诺,就像您无法从函数返回多个值一样 。承诺在概念上代表一个随时间变化的值,所以当你可以表示复合值时,你不能在承诺中放置多个值。

You can't resolve a promise with multiple properties just like you can't return multiple values from a function. A promise conceptually represents a value over time so while you can represent composite values you can't put multiple values in a promise.

一个承诺固有地用单个值解析 - 这是Q如何工作的一部分, Promises / A +规范如何工作以及如何抽象有效。

A promise inherently resolves with a single value - this is part of how Q works, how the Promises/A+ spec works and how the abstraction works.

最接近的是使用 Q.spread 并返回数组或使用ES6解构如果支持或者您愿意使用像BabelJS这样的转换工具。

The closest you can get is use Q.spread and return arrays or use ES6 destructuring if it's supported or you're willing to use a transpilation tool like BabelJS.

关于在承诺链中传递上下文,请参阅

As for passing context down a promise chain please refer to Bergi's excellent canonical on that.

这篇关于你如何正确地从承诺中返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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