如何通过异步等待从其他Promise获取结果?

时间:2019-01-08 17:03:57

标签: javascript async-await es6-promise serverless-framework

我尝试使用无服务器框架,现在我有2个文件:

  1. server.js =>处理与monggoDB的连接
  2. handler.js =>这将处理从无服务器框架到lambda的功能

我想先从server.js获取结果,然后再执行下一步。

我正在尝试使用await dan将结果保存到变量中, handler.js中的进程将同步运行,但startServer()的结果未定义

// server.js
const mongoose = require('mongoose');
const dbHost = require('../config/keys').mongoURI;

module.exports = async () => {
  mongoose.Promise = global.Promise;
  mongoose.set('useFindAndModify', false);

  return await mongoose
    .connect(
      dbHost,
      { useNewUrlParser: true }
    )
    .then(res => {
      console.log('MongoDB Connected', res);
      return res;
    })
    .catch(err => {
      console.error(err);
      console.error('MongoDB Not Connected');
      return err;
    });
};

// handler.js
const startServer = require('./db/server');
module.exports.hello = async (event, context) => {
  let tryConnect = await startServer();
  console.log('server is running', tryConnect);
  return { statusCode: 200, body: JSON.stringify(tryConnect) };
};

如何从嵌套的async-await中正确地从await中获得结果?

谢谢

2 个答案:

答案 0 :(得分:0)

您也许可以返回在 df1.to_csv('example.csv', sep='\t') 之后得到的值:

await

答案 1 :(得分:0)

如果您使用mongoose.connect,则无需在await上使用回调函数。回调函数用于Promise,而不用于await,在try/catch中使用async/await

// server.js
const mongoose = require('mongoose');
const dbHost = require('../config/keys').mongoURI;

module.exports = async () => {
    mongoose.Promise = global.Promise;
    mongoose.set('useFindAndModify', false);

    return await mongoose
        .connect(
            dbHost, {
                useNewUrlParser: true
            }
        );
};

// handler.js
const startServer = require('./db/server');
module.exports.hello = async (event, context) => {
    let tryConnect = {};
    try {
        tryConnect = await startServer();
        console.log('MongoDB Connected', tryConnect);
    } catch (err) {
        console.error(err);
        console.error('MongoDB Not Connected');
    }
    console.log('server is running', tryConnect);
    return {
        statusCode: 200,
        body: JSON.stringify(tryConnect)
    };
};