如何在 Nodejs Azure Function App 中正确使用 await/async

How to use await/async properly in Nodejs Azure Function App

我正在尝试使用 nodejs 堆栈编写代码以连接 azure 函数应用程序内的 snowflake。这是我写的代码。

async function af2snf() 
{
console.log("starting connection");
var snowflake = require('snowflake-sdk');
// Create a Connection object that we can use later to connect.
console.log("prep conn");
var connection = snowflake.createConnection( {
    account: "myaccountname",
    username: "myusername",
    password: "mypass",
    database: "dbname",
    schema: "schemaname"
    }
    );
console.log("making connection");

var conn_id = connection.connect( 
        function(err, conn) {
            if (err) {
                console.error('Unable to connect: ' + err.message);
                } 
            else {
                console.log('Successfully connected to Snowflake.');
                // Optional: store the connection ID.
                connection_ID = conn.getId();
                }
            }
        )
return conn_id.getId();
}

console.log("outside fucntion");
console.log(af2snf());
console.log("executed fucntion");

我得到的输出是:

outside fucntion
starting connection
prep conn
making conn
Promise { <pending> }
executed fucntion
Successfully connected to Snowflake.

但我需要的是:

outside fucntion
starting connection
prep conn
making conn
Successfully connected to Snowflake.
Promise { <pending> }
executed fucntion

我是 nodejs 的新手。请帮我解决这个问题

af2nsf 需要 return 一个承诺 :

async function af2snf() {
  return new Promise((resolve,reject)=>{
   console.log("starting connection");
   var snowflake = require('snowflake-sdk');

   // Create a Connection object that we can use later to connect.
   console.log("prep conn");
   var connection = snowflake.createConnection( {
    account: "myaccountname",
    username: "myusername",
    password: "mypass",
    database: "dbname",
    schema: "schemaname"
    });
   console.log("making connection");

   connection.connect( async function(err, conn) {
            if (err) {
                console.error('Unable to connect: ' + err.message);
                return reject(err);
            } 
            else {
                console.log('Successfully connected to Snowflake.');
                // Optional: store the connection ID.
                var conn_id = await conn.getId();
                return resolve(conn_id);
             }
      })
  });
}

console.log("outside fucntion");
af2snf().then(conn_id=>{
   console.log(conn_id);
   console.log("executed fucntion");
}).catch(err=>{
   console.error(err);
});