Typescript-异步、等待和承诺不在等待
我正在尝试连接到Snowflake DB,但程序并没有等待connect函数完成,尽管我使用的是async await,但它仍在继续Typescript-异步、等待和承诺不在等待,typescript,async-await,promise,Typescript,Async Await,Promise,我正在尝试连接到Snowflake DB,但程序并没有等待connect函数完成,尽管我使用的是async await,但它仍在继续 async function createConnection() { try { return new Promise<any>(async (resolve, reject) => { // Create a Connection object that we can use later to connect.
async function createConnection() {
try {
return new Promise<any>(async (resolve, reject) => {
// Create a Connection object that we can use later to connect.
const connection = snowflake.createConnection({
account: envs.account,
username: envs.user,
password: envs.password,
}
);
// Try to connect to Snowflake, and check whether the connection was successful.
connection.connect(
(err, conn) => {
if (err) {
console.error('Unable to connect: ' + err.message);
}
else {
console.log('Successfully connected to Snowflake.');
}
}
);
resolve(connection);
})
}
catch (e) {
console.error(e);
}
}
async function main() {
const connection = await createConnection();
if (connection == undefined || !connection?.isUp()) {
console.error('Failed to connect to snowflake...');
return;
}
谢谢你的帮助 承诺应解析为
conn
,您可以通过传入connection.connect的回调访问该连接
//如果没有在内部使用'wait',则不必显式标记为'async'。
函数createConnection(){
返回新承诺((解决、拒绝)=>{
//创建一个连接对象,我们可以稍后使用它进行连接。
const connection=snowflake.createConnection({
账户:环境账户,
用户名:envs.user,
密码:envs.password,
});
//尝试连接到Snowflake,并检查连接是否成功。
连接(
(呃,康涅狄格州)=>{
如果(错误){
log(`无法连接:${err.message}`);
}
否则{
console.log('已成功连接到雪花');
}
//`conn`可能未定义,但您的主函数似乎处理该检查。。。
决议(康涅狄格州);
}
);
});
}
异步函数main(){
const connection=wait createConnection();
if(connection==未定义的| |!connection?.isUp()){
console.error('未能连接到雪花…');
返回;
}
}
createConnection
函数和executor函数(传递给promise构造函数的函数)不应该是异步的。请参阅:就您的问题而言,resolve(连接)
-此语句应位于连接的回调函数内的else
块内。connect(…)
Failed to connect to snowflake...
Successfully connected to Snowflake.