首页 \ 问答 \ 将两个promise的结果输出到一个对象中(Output results of two promises into a single object)

将两个promise的结果输出到一个对象中(Output results of two promises into a single object)

我有两个创建承诺的异步函数。 这两个函数都使用相同的输入i

async function1(i) {}
async function2(i) {}

我将用不同的值为我的输入多次调用这些函数,并且我希望尽可能提高代码的效率,因此我想排列承诺并使用Promise.all()并行运行它们。

然而,我想得到一个单一的结果作为我的最终输出,这将是一个像这样的对象数组:

[
  {
    input: i,
    result1: result1,
    result2: result2
  },
  ...
]

我通过两个独立的步骤完成了这个工作:

async function function1(i) {
  return i * i
}

async function function2(i) {
  return i * i * i
}

async function main() {
  var promises = []

  for (let i = 0; i < 10; i++) {
    let promise = function1(i)
      .then(function(result1) {
          return {i:i, result1:result1}
      });

    promises.push(promise)
  }

  var final = await Promise.all(promises)
  
  var promises2 = [];
  
  for (let i = 0; i < 10; i++) {
    let promise = function2(i)
    .then (function(result2) {
      final[i]['result2'] = result2;
    });
    
    promises2.push(promise);
  }
  
  await Promise.all(promises2)
  
  console.log(final)

}

main()

不过,我觉得这可以通过一个Promise.all() 。 你能告诉我如何?


I have two asynchronous functions which create promises. Both functions use the same input i.

async function1(i) {}
async function2(i) {}

I will be calling these functions multiple times with different values for my input, and I want to make my code as efficient as possible, so I want to queue the promises and have them run in parallel using Promise.all().

However, I want to get a single result as my final output, which will be an array of objects like so:

[
  {
    input: i,
    result1: result1,
    result2: result2
  },
  ...
]

I have accomplished this in two descrete steps:

async function function1(i) {
  return i * i
}

async function function2(i) {
  return i * i * i
}

async function main() {
  var promises = []

  for (let i = 0; i < 10; i++) {
    let promise = function1(i)
      .then(function(result1) {
          return {i:i, result1:result1}
      });

    promises.push(promise)
  }

  var final = await Promise.all(promises)
  
  var promises2 = [];
  
  for (let i = 0; i < 10; i++) {
    let promise = function2(i)
    .then (function(result2) {
      final[i]['result2'] = result2;
    });
    
    promises2.push(promise);
  }
  
  await Promise.all(promises2)
  
  console.log(final)

}

main()

However, I feel like this can be accomplished using a single Promise.all(). Can you tell me how?


原文:https://stackoverflow.com/questions/50498186
更新时间:2022-02-21 21:02

最满意答案

也许如果你迭代散列键并返回包含它的数组,或者如果你创建另一个散列。 第二,它可能看起来像这样:

my %newhash;
for my $key (keys %hash1) {
  my @list = split /, / => $hash1{$key}[0];
  # or perhaps: my @list = map split(/, /, $_), @{ $hash1{$key} };
  for (@list) {
    $newhash{$_} = $key;
  }
}
$newhash{mexico} eq 'a'; #true

这不是非常有效,但它会起作用。


Maybe if you either iterate through the hash keys and return the array containing it, or if you create another hash. For the second, it might look like this:

my %newhash;
for my $key (keys %hash1) {
  my @list = split /, / => $hash1{$key}[0];
  # or perhaps: my @list = map split(/, /, $_), @{ $hash1{$key} };
  for (@list) {
    $newhash{$_} = $key;
  }
}
$newhash{mexico} eq 'a'; #true

This isn't terribly efficient, but it will work.

相关问答

更多
  • 您需要遍历第一个散列(键/值)中的散列键并累计您在另一个散列(值/计数)中找到的每个项目的计数。 如果你想将键值和重复值一起显示出来,你的第二个散列表就不会那么简单了,因为对于每个重复值,你都会得到一组键值(它们都具有相同的值)。 在这种情况下,只需将该键积累到一个数组中,然后对其元素进行计数。 也就是说,你的第二个哈希值将会是(value / [key1,key2,key3 ...]) my %hash = ( key1 => "one", key2 => "two", key3 => "one", ke ...
  • 我的%散列; 用键$ K插入一个项目$ V? $ hash {$ K} = $ V 找到一个特定的名字/键$ K? if (exists $hash{$K}) { print "it is in there with value '$hash{$K}'\n"; } else { print "it is NOT in there\n" } 删除特定的名称/密钥? 删除$ hash {$ K} 将名称和日期作为关键字并将整个项目作为值? 简单的方 ...
  • 如果我正确地理解了你的话,这似乎可以做到这一点(最后使用Dumper()打印哈希值只是为了向你展示hashref包含的内容): #!/usr/bin/perl -w use strict; use Data::Dumper; my $dir = $ENV{PWD}; opendir( DIR, $dir ) or die $!; my @files = grep { -f "$dir/$_" } readdir( DIR ); my $hash = { $dir => { cou ...
  • 首先,在你的内部循环中,你有 for my $value ( @{$hash{$value1}} ) { print KEYS "$value "; } 什么是$value1 ? 我想你想用$key 。 始终use strict; use warnings use strict; use warnings来警告未定义的值和未声明的变量。 接下来,让我们看看当我们做什么时会发生什么 my %hash; push @{ $hash{ $value1[$_] } }, "(value$_)" fo ...
  • 也许如果你迭代散列键并返回包含它的数组,或者如果你创建另一个散列。 第二,它可能看起来像这样: my %newhash; for my $key (keys %hash1) { my @list = split /, / => $hash1{$key}[0]; # or perhaps: my @list = map split(/, /, $_), @{ $hash1{$key} }; for (@list) { $newhash{$_} = $key; } } $newhash{ ...
  • 这个简短的程序可以满足你的要求。 它将索引散列到每个数组中。 我在数组@keys使用了散列键的单独排序列表,因为直接从散列中获取它们将导致不可预知的顺序,并且看起来您需要按特定顺序输出。 use strict; use warnings; my %aggrs_by_node = ( node1 => ['a1_1','a1_2'], node2 => ['a2_1','a2_2','a2_3'], hello => ['ah_1','ah_2','ah_3'], node3 => ['a3 ...
  • my $City = { city1 => { Street1 => [ 'high_street', 2], street2 => [ 'low_street', 2], }, city2 => { Street1 => [ 'high_street1', 2], street2 => [ 'low_street2', 2], }, city3 => { Street1 => [ 'hi ...
  • while (my ($k, $v) = each %$vsnhash) { print "$k: @$v\n"; } while (my ($k, $v) = each %$vsnhash) { print "$k: @$v\n"; }
  • 使用List :: Util(它是core perl的一部分)中的reduce函数。 #!/usr/bin/perl use strict; use warnings; use List::Util qw/reduce/; my %hash = ( "a" => { "b" => 2, "c" => 1, }, "d" => { "e" => 4, }, ); my $key = 'a'; print "For key: ...
  • 如果你解释了你的数据中的数字是什么意思,我想这可能会更清楚 你有什么是有向图 。 原始数据仅代表每个节点的子节点,而您想要的结果列出所有后代 您必须构建一个包含所有已知信息的数据结构,并允许您查询有关两个节点之间关系的信息 我认为CPAN Graph模块套件可能会满足您的所有需求。 不幸的是,我目前正在使用我的平板电脑,因此我无法编写示例代码。 但它应该是直截了当的,如果我幸免,我会在早上检查这个问题 更新 这是我打算的代码。 在图中,所有数据点都称为边 ,所有关系都称为边 。 该程序通过分配来自%hash ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)