Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用异步函数的结果填充数组_Javascript_Arrays_Asynchronous_Es6 Promise - Fatal编程技术网

Javascript 用异步函数的结果填充数组

Javascript 用异步函数的结果填充数组,javascript,arrays,asynchronous,es6-promise,Javascript,Arrays,Asynchronous,Es6 Promise,我需要设置一个对象数组,但是它的属性需要来自异步函数 要做到这一点,我在数组上运行.map(),并对每个元素执行我需要执行的任何操作,但我需要它们的异步函数的结果 我现在这样做的结果是PromiseStatus和PromiseValue,这不是我想要的。我基本上只希望数组中有我的PromiseValue 这是我目前的代码: function processMyArray (array) { const processedArray = array.map(x => { retu

我需要设置一个对象数组,但是它的属性需要来自异步函数

要做到这一点,我在数组上运行
.map()
,并对每个元素执行我需要执行的任何操作,但我需要它们的异步函数的结果

我现在这样做的结果是
PromiseStatus
PromiseValue
,这不是我想要的。我基本上只希望数组中有我的
PromiseValue

这是我目前的代码:

function processMyArray (array) {
  const processedArray = array.map(x => {
    return myAsyncFunction(x)
      .then((result) => {
        const { attribute1, attribute2 } = result
        return {
          attribute1,
          attribute2
        }
      })
  })
  return processedArray
}

// the rough code for myAsyncFunction()
 myAsyncFunction (data) {
    return Promise.all(
      [
        this.getAttribute1(data),
        this.getAttribute2(data)
      ]
    )
    .then(([attribute1, attribute2]) => {
      return {
        attribute1, attribute2
      }
    })
  }

将映射的

Promise.all(array.map(...))
或者使用凉爽的ES 7材料(等待循环):


将映射的文件包装到
Promise.all(array.map(…)
@Jonasw,就是这样!非常感谢对我来说,关键是知道
array.forEach
不起作用,但我必须为(x of array)使用一个简单的
。我从未意识到。谢谢
async function processMyArray (array) {
  const result = [];
  for(const x of array){ //x is a bad name by the way
    const { attribute1, attribute2 } = await myAsyncFunction(x);
    result.push({ attribute1, attribute2 });
  }
  return result;
}