node异步方法的异步调用与同步调用实现方法示例
作者:他强任他强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进行操作,与逻辑主体无关的异步操作部分则是直接使用异步调用即可,这样就避免了线程的阻塞。
