你需要理解JavaScript的三种处理异步代码的方式,然后选择合适的方式:
- 回调
- Promise
- async/await
回调方式:
function search_flight(mdate,fc,des, callback) {
connection.query('select * from flight_info\n' +
' where date= "'+mdate+'"&& from_city="'+fc+'" && to_city= "'+des+'" ;',function (error, results, fields) {
if (error) throw error;
console.log(results[0]);
callback(results);
}
);
};
function test(){
search_flight(lmdate,lfc,ldes, function(results){
console.log(results);
});
}
test();
Promise 方式
function search_flight(mdate,fc,des) {
return new Promise(function (resolve,reject){
connection.query('select * from flight_info\n' +
' where date= "'+mdate+'"&& from_city="'+fc+'" && to_city= "'+des+'" ;',function (error, results, fields) {
if (error) reject({err:1, msg:error});
resolve({err:0, results});
}
);
})
};
function test(){
search_flight(lmdate,lfc,ldes).then(function (ret){
if(!ret.err){
console.log(ret.results)
}
});
}
test();
异步函数方式
async function search_flight(mdate,fc,des) {
return new Promise(function (resolve,reject){
connection.query('select * from flight_info\n' +
' where date= "'+mdate+'"&& from_city="'+fc+'" && to_city= "'+des+'" ;',function (error, results, fields) {
if (error) reject({err:1, msg:error});
resolve({err:0, results});
}
);
})
};
async function test(){
let ret = await search_flight(lmdate,lfc,ldes);
if(!ret.err){
console.log(ret.results)
}
}
test();