如何从云功能调用同步子功能

时间:2018-07-25 12:23:58

标签: node.js asynchronous google-cloud-functions synchronous

我想同步运行所有功能。但是,如果我执行类似下面的代码的操作,则在分配返回值之前将响应发送回去。

index.js

exports.cfTest = (req, res) => {
    try {
        result = columnCount(
         'project','dataset','table'
        );
        console.log('sending response');
        res.send('<OUTPUT>' + result + '</OUTPUT>');
    } catch (err) {
        res.status(500).send('<ERROR>' + err + '</ERROR>');     
    }
};

function columnCount(projectId, bqDataset, bqTable) {

    const BigQuery = require('@google-cloud/bigquery');
    const bigquery = new BigQuery({projectId: projectId});

    var result;

    bigquery
    .dataset(bqDataset)
    .table(bqTable)
    .get()
    .then(results => {
        result = results[1].schema.fields.length;   
    })
    .catch(err => {
        result = null;
    });

    console.log('returning ' + result);
    return result;
}

即控制台输出类似于:

<OUTPUT>undefined</OUTPUT> 

,并且在Stackdriver日志中将显示如下执行顺序:

 2018-07-25 10:00:00 - Function execution started
 2018-07-25 10:00:01 - sending response
 2018-07-25 10:00:02 - Function execution took 2000 ms, finished with status code: 200
 2018-07-25 10:00:03 - returning 5

这是将执行锁定为仅同步行为的一种优雅方法吗?

解决方案

Alexandru建议的异步/等待方法有效!谢谢亚历山德鲁。

NB:但是不适用于标准/ GA Cloud功能。您必须使用Google Cloud Functions Node.js v8 Beta

1 个答案:

答案 0 :(得分:2)

是的,你可以看看async/await

您的代码最后将看起来像这样:

async function columnCount(projectId, bqDataset, bqTable) {
  const BigQuery = require('@google-cloud/bigquery');
  const bigquery = new BigQuery({ projectId: projectId });

  try {
    let results = await bigquery
      .dataset(bqDataset)
      .table(bqTable)
      .get();

    return results[1].schema.fields.length;
  } catch (err) {
    return null;
  }
}

第二个

exports.cfTest = async (req, res) => {
  try {
      result = await columnCount(
       'project','dataset','table'
      );
      console.log('sending response');
      res.send('<OUTPUT>' + result + '</OUTPUT>');
  } catch (err) {
      res.status(500).send('<ERROR>' + err + '</ERROR>');     
  }
};