0

I have some really heavy promise based code, that I'm looking to break up, and move over to async/await.

I'm running into an issue however - what's a good design pattern for the following problem. Essentially I have something that is reliant on the previous step of the 'promise'.

How can I pass the value down to the block below? Or just init it to something so I can keep it around?

Thanks, Ollie

let sess;

// if has experts
if (!_.isEmpty(data.expertIds)) {
  // create expert campaign sessions
  const sessions = await util.createSessions(data.expertIds, newCampaignId);
  Promise.all(sessions)
    .then((s) => {
      // if sessions created, set this var to true!
      sess = true;
      debug('Sessions created');
    })
    .catch((error) => { throw error; });
}

debug(sess)          // undefined
debug(await sess)    // undefined
...lots and losts more code...

let newCampaignId;
// save the new campaign as a draft
newCampaign
  .save()
  .then((campaign) => {
    newCampaignId = campaign._id;
    debug('New campaign saved', campaign);
  })
  .catch((error) => { throw error; });

debug(newCampaignId)        // undefined
debug(await newCampaignId)  // undefined
1
  • 1
    you assign the values returned by a promise as variables. s = await Promise.all(sessions) Commented Nov 18, 2017 at 20:46

1 Answer 1

2

You need to return values from then() if you want them later. then() returns a promise -- this returned promise is what you need to await. This is the final resolved value of the promise, that you are trying to await. For example:

// save the new campaign as a draft
var a_promise = newCampaign
.save()
.then((campaign) => {
    debug('New campaign saved', campaign._id);
    return campaign._id // make sure you return something
})

debug(await a_promise)  // should be defined now 

Returning campaign._id is essential here.

The construct you've made is a little unwieldy though. Since save() returns a promise you should be able to simply do:

let campaign = await newCampaign.save()
debug(campaign._id)

Of course all this presumes you are inside an async function.

Sign up to request clarification or add additional context in comments.

1 Comment

The .catch((error) => { throw error; }); line, repeated from the post, is redundant and can be removed. What it does is reject the promise returned by catch if the promise catch was called on was rejected!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.