简体   繁体   中英

Child functions and async await

In one of my API endpoints I fetch a json resource (1) from the web and edit it to fit my needs. In the "lowest" or "deepest" part of the tree I'm trying to fetch another resource and add it to the final json object. I'm relatively new to async/await but am trying to move away from the "old" Promise s since I see the advantage (or the gain) of using async/await.

The object from (1) looks like;

 const json = { date, time, trips: [{ name, legs: [{ id }, { id } ] }] }; 

Here's how I "reformat" and change the json object;

 { date, time, trips: json.trips.map(trip => formatTrip(trip)) }; function formatTrip(trip) { return { name, legs: trip.legs.map(leg => formatLeg(leg)) }; }; async function formatLeg(leg) { const data = await fetch(); return { id, data }; }; 

The problem with this is that after I've "reformatted/edited" the original json to look how I want it (and ran through all format... functions) the legs objects are empty {} .

I figured this might be due to the async/await promises not finishing. I've also read that if a child-function uses async/await all the higher functions has to use async/await as well.

Why? How can I rewrite my code to work and look good? Thanks!

EDIT:

I updated my code according to Randy's answer. getLegStops(leg) is still undefined/empty.

 function formatLeg(leg) { return { other, stops: getLegStops(leg) }; }; function getLegStops(leg) { Promise.all(getLegStopRequests(leg)).then(([r1, r2]) => { /* do stuff here */ return [ /* with data */ ]; }); }; function getLegStopRequests(leg) { return [ url1, url2 ].map(async url => await axios.request({ url })); }; 

Two things lead you to want to nest these Promises:

  1. The old way of thinking about callbacks and then Promises
  2. Believing the software process must match the data structure

It appears you only need to deal with the Promises once if I understand correctly.

Like this:

 async function getLegs(){ return trip.legs.map(async leg => await fetch(...)); // produces an array of Promises } const legs = Promise.all(getLegs()); function formatLegs(legs) { // do something with array of legs }; function formatTrip(){ //format final output } 

EDIT: per your comment below, this snippet represents what I've demonstrated and what your goal should look like. Please review your code carefully.

 const arr = [1, 2, 3, ]; const arrPromises = arr.map(async v => await new Promise((res) => res(v))); const finalPromise = Promise.all(arrPromises); console.log(finalPromise.then(console.log)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM