2017-10-25 2 views
0

Ich muss ein Array von Objekten einrichten, aber seine Attribute müssen von einer asynchronen Funktion kommen.Füllen eines Arrays mit Ergebnissen einer Async-Funktion

Um das zu tun, führe ich .map() auf dem Array, und tun was immer ich tun muss für jedes Element, aber ich brauche das Ergebnis der Async-Funktion für sie.

Die Art, wie ich es gerade mache, bekomme ich PromiseStatus und PromiseValue als mein Ergebnis, das ist nicht was ich will. Ich möchte im Grunde nur meine PromiseValue in meinem Array.

Hier ist meine aktuellen Code ist:

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

Wickeln Sie die in 'Promise.all (array.map (...)) abgebildet' –

+0

@Jonasw, das war's! Vielen Dank – theJuls

Antwort

1

Entweder die

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

oder benutzen Sie kühlen ES 7 Sachen in

abgebildet wickeln (warten in for-Schleifen):

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; 
} 
Verwandte Themen