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

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

问题描述

我最近遇到了几次某种情况,我不知道如何正确解决.假设以下代码:

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

现在可能会出现一种情况,我想在 afterSomethingElse 中访问 amazingData.

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 a 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.

推荐答案

您无法解析具有多个属性的 Promise,就像您无法从函数中返回多个值一样.一个承诺在概念上代表一个随时间变化的值,因此虽然您可以表示复合值,但不能在一个承诺中放入多个值.

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.

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.

关于在承诺链中传递上下文,请参考 Bergi 在这方面的优秀规范.

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

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

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