node异步方法的异步调用与同步调用实现方法示例
更新时间:2023年05月29日 09:14:30 作者:他强任他强03
这篇文章主要介绍了node异步方法的异步调用与同步调用实现方法,结合实例形式分析了node.js异步操作类的封装以及同步、异步两种调用方式,需要的朋友可以参考下
异步方法(class封装与exports导出):
module.exports = class QueryLarbor { querydata() { return new Promise((resolve,reject) => { client .search({ index: configs.labor_index, type: type, body: JSON.stringify(esbody), }) .then((res) => // console.log(JSON.stringify(res)) res.hits.hits.map((v) => // console.log(v._source) resolve(v._source) ) ) .catch((err) => console.error(err)); }) } };
异步调用:
const QueryLarbor = require("./QueryLarbor"); let idl_cost_per_hour; let queryLarbor = new QueryLarbor(); //异步调用获取值 queryLarbor.querydata().then((res) => { console.log(res); });
同步调用:
const QueryLarbor = require("./QueryLarbor"); let idl_cost_per_hour; let queryLarbor = new QueryLarbor(); //同步调用获取值,自调用方法 (async() => { let esData = await queryLarbor.querydata() console.log(esData); })();
注:笔者在使用异步操作的时候对于需要回调函数处理的逻辑通常会结合then进行操作,与逻辑主体无关的异步操作部分则是直接使用异步调用即可,这样就避免了线程的阻塞。
相关文章
Node.js中使用Log.io在浏览器中实时监控日志(等同tail -f命令)
这篇文章主要介绍了Node.js中使用Log.io在浏览器中实时监控日志,Log.io等同于tail -f命令,但更强大,需要的朋友可以参考下2014-09-09npm install安装报错:gyp info it worked if it ends with
今天新启动一个项目,在 npm install 安装依赖项时出现报错,所以下面这篇文章主要给大家介绍了关于npm install安装报错:gyp info it worked if it ends with ok的解决方法,需要的朋友可以参考下2022-07-07mongodb初始化并使用node.js实现mongodb操作封装方法
这篇文章主要介绍了mongodb初始化并使用node.js实现mongodb操作封装方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-04-04
最新评论