Search code examples
javascriptasync-awaites6-promise

Is it possible to use one await keyword for resolving a set of sequential promises


Perhaps this is a limitation of the language, but I am trying to figure out how I could get away with using a single await keyword for a set of sequential promise resolutions. I am trying to achieve something readable, like the following:

const workoutExercises = await Workout.get(1).workoutExercises;

Workout.get accesses a database, and so returns a Promise. The promise resolves to an instance of Workout, which has a getter method on the instance called workoutExercises, which is also a Promise that resolves to an array of WorkoutExercises.

The above code does not work, and only waits for Workout.get to resolve; doesn't also wait for .workoutExercises to resolve. The following below code examples DO work, but I am trying to achieve a one-liner / more readability:

1:

const workoutExercises = await (await Workout.get(1)).workoutExercises;

2:

const workout = await Workout.get(1);
const workoutExercises = await workout.workoutExercises;

Edit #1 Updated the title and description to clarify that the problem doesn't revolve around the resolution of a Promise chain, but the resolution of a Promise based on the resolution of a preceding Promise.

Workout.get --> <Promise> --> workout --> .workoutExercises --> <Promise> -> desired result


Solution

  • Use .then() on the results of .get(1), and extract workoutExercises. The one liner is very readable.

    Example:

    (async() => {
    
      const Workout = {
        get: () => Promise.resolve({
          workoutExercises: Promise.resolve(3)
        })
      };
    
      const workoutExercises = await Workout.get(1).then(w => w.workoutExercises);
    
      console.log(workoutExercises)
    
    })()