2017-10-25 5 views
0

オブジェクトの配列を設定する必要がありますが、その属性は非同期関数から来る必要があります。非同期関数の結果で配列を塗りつぶす

これを行うには、.map()を配列に実行し、各要素で何を行う必要があるかを行いますが、そのためには非同期関数の結果が必要です。

私が今やっているやり方は、私が好きなものではないので、PromiseStatusPromiseValueが結果として得られます。私は基本的に私のPromiseValueを私の配列に入れたいだけです。 (forループで待つ)

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 
     } 
    }) 
    } 
+1

ラップPromise.all(array.map(...))にマップされています –

+0

@Jonasw、それでした!本当にありがとう – theJuls

答えて

1

どちらかが

Promise.all(array.map(...)) 

またはクールES 7のものを使用するにマッピングされたラップ:ここ

が私の現在のコードです

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; 
} 
関連する問題