Ollie
Ollie

Reputation: 1134

Saving the 'result' value of async code node.js

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

Upvotes: 0

Views: 215

Answers (1)

Mark
Mark

Reputation: 92440

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.

Upvotes: 2

Related Questions