在node.js应用程序中,我需要执行以下操作:(当然,伪代码)
if(loadedData is empty){
loadDatafromDatabase <<---- this one is async
}
useLoadedData
当然,从数据库加载数据是一个异步过程,因此useLoadedData尝试在加载完成之前使用数据。在继续之前,是否有任何干净的方法来等待loadDataFromDatabase返回其结果?
我已经看到很多人提到回调是一种正确的解决方案,所以我很想做类似的事情:
if(loadedData is empty){
loadDataFromDatabase( callback useLoadedData )
}else{
useLoadedData
}
但是对我来说看起来很脏。有更好的方法吗?
谢谢!
如果可以包含节点光纤,则可以尝试使用wait.for
https://github.com/luciotato/waitfor
var wait=require('wait.for');
function process(){
if(!data){
data = wait.for(loadDatafromDatabase);
// loadDatafromDatabase is *standard* async
// wait.for will pause the fiber until callback
}
useLoadedData(data);
}
wait.launchFiber(process);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句