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 中使用 axios 配置代理并实现图片并发下载
这篇文章主要介绍了如何在Node.js中使用axios配置代理并实现图片并发下载,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧2024-07-07
npm install --save 、--save-dev 、-D、-S&nb
这篇文章主要介绍了npm install --save 、--save-dev 、-D、-S 的区别与NODE_ENV的配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-08-08


最新评论