node.js - expressJs - Wait for a promise inside a loop -
novice question; need create conditional loop makes call database. value returned promise determines if should break out of loop follows:
let id, caged; { caged = false; id = models.cage.generateid(); caged = models.cage.findone({ where: { dispatchlabelid: id } }); } while( caged );
can please advise how can structure code?
you can using promises , recursive function calls:
let getcage = () => { return models.cage .generateid() .then(id => models.cage.findone({ where: { dispatchlabelid: id } })) .then(caged => { if (caged) { return caged; } return getcage(); }); }
in case if can use node.js v7.6 or higher can avoid using recursive function calls , implement using async/await
:
let getcage = async () => { try { { let id = await models.cage.generateid(); let caged = await models.cage.findone({ where: { dispatchlabelid: id } }); if (caged) { return caged; } } while (true); } catch (err) { console.log(err); } }
Comments
Post a Comment