【问题标题】:Promise.all() with map() returns undefined items in arrayPromise.all() 和 map() 返回数组中未定义的项目
【发布时间】:2018-07-24 00:40:25
【问题描述】:

尝试生成一个随机数数组:

const arr = await generateValues(20, 500);

async function generateValues(numOfValues, max){
  return await Promise.all(
    new Array(numOfValues).map(() => Math.ceil(Math.random() * max))
  );
}

const arr 返回一个长度为 20 的数组,但都是 undefined

【问题讨论】:

  • 您只能在异步函数中使用 await 您的代码会返回此错误:SyntaxError: await is only valid in async function

标签: javascript async-await es6-promise


【解决方案1】:

map 会忽略数组中的空元素,所以你必须先使用fill

var arr = new Array( 20 ).fill( 0 ).map( () => { ... } )

【讨论】:

    【解决方案2】:

    您可能不知道map,它不适用于空白或空数组。您必须使用fill 插入至少一个元素。

    试试看。

    async function generateValues(numOfValues, max){
      return await Promise.all(
        new Array(numOfValues).fill(0).map(() => Math.ceil(Math.random() * max))
      );
    }
    const arr = await generateValues(20, 500);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 2016-04-21
      • 1970-01-01
      • 2019-07-24
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多