我想在执行mapSeries后返回querys(function)
我该怎么做?请帮帮我!
async querys(querys) {
const pool = await poolPromise;
if (pool != null) {
const transaction = new sql.Transaction(pool);
await new Promise(resolve => transaction.begin(resolve));
const request = new sql.Request(transaction)
try {
let results = []
// ------------- Series -------------
async.mapSeries(querys, async (query, callback) => {
console.log('----------')
const result = await request.query(query);
// return result.recordset;
results.push(result.recordset);
}, async (err) => {
if (err) {
throw new Error(err);
}
else {
await transaction.commit();
}
});
console.log('hello');
// -------------- return ---------------
return [true, results];
} catch(err) {
await transaction.rollback();
return [false, err];
}
}
else {
return [false, 'connect error'];
}
},
查询
期望输出:[true, [object], [object]…)
实际输出:[true, []]
self answer
添加承诺
async querys(querys) {
return new Promise( async resolve => {
const pool = await poolPromise;
if (pool != null) {
const transaction = new sql.Transaction(pool);
await new Promise(resolve => transaction.begin(resolve));
const request = new sql.Request(transaction)
async.mapSeries(querys, async (query, callback) => {
const result = await request.query(query);
return result.recordset;
}
, async (err, results) => {
if (err) {
console.log(err);
console.log('rollback');
await transaction.rollback();
resolve({isError: true, err: '데이터 가져오기 오류'});
}
else {
await transaction.commit();
resolve({isError: false, data: results})
}
});
}
else {
resolve({isError: true, err: '데이터에 연결할 수 없습니다.'});
}
});
},