我在test.js文件中有以下函数
null
module.exports.connected = connected;
async function connected() {
const mysql = require('mysql');
const connection = await mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
port : 3311
});
await connection.connect(function(err) {
if (err) {
console.log("cannot connect to database");
}
console.log("connected");
});
};
null
并使用下面的代码调用它
null
const sql = require('./my_mysql');
sql.connected().then(function (data) {
console.log("aaa");
});
null
但为什么先印“AAA”,再印“连接”呢?
While必须等待响应
在分配中使用await,如下所示
async function handler (req, res) {
let response;
try {
response = await request('https://user-handler-service') ;
} catch (err) {
logger.error('Http error', err);
return res.status(500).send();
}
...
}
不能使用await for函数,因为await运算符只在异步函数中有意义。