0

我正在尝试编写代码以使用 nodejs 堆栈与天蓝色函数应用程序中的雪花连接。这是我编写的代码。

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很陌生。请帮我解决这个问题

4

1 回答 1

1

af2nsf需要返回一个承诺:

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);
});
于 2020-06-25T10:44:33.093 回答