-2

I have the following simplified functions:

create: async (x) => {
 ...
 id = await functionX(); //among the other it stores url in DB
 const2 = await functionY(id); //this function was built to retrieve value from DB stored by functionX using id.

 return const2;
}


functionY (id) {
 const query = data.base.get(id)
 return query.url
}

Unfortunately, id resolves before storing to DB and therefore query.url becomes undefined.

I was looking for something simple like:

const2 = await (functionY(id)) ? functionY(id) : null

I know it's wrong, but anyways, how do I deal with such cases?

Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
  • If `functionX()` resolves before it's done with its work, then it's just broken and the code in that function needs to be fixed. There is no other way to know when it's done other than fixing its implementation. Your question needs to show that code so we can help you fix it. – jfriend00 Jul 04 '18 at 15:10
  • FYI, `await` has no magic powers to know when anything is done. It awaits a promise and proceeds when that promise is resolved. So, if something isn't awaiting what you want, then you have to fix when the promise is resolved. There is no other way. – jfriend00 Jul 04 '18 at 15:11

1 Answers1

0

Return a promise from functionX using

new Promise((resolve, reject) => {})

And only resolve the promise once you get a confirmation of the result from the database.

Currently,

await functionX

Would only wait till the time any data is returned to it if it is not a promise.

Ankit Sharma
  • 1,674
  • 8
  • 11