【问题标题】:(Serverless Framework Module) wait for promise to resolve before return statement(无服务器框架模块)在return语句之前等待promise解决
【发布时间】:2016-02-17 00:52:44
【问题描述】:

无服务器框架模块是否可以在返回之前等待承诺的“解决”?

我知道 promise 本身无法做到这一点,但是不同的框架/库(expressJasminehapijs 等)通过定义何时返回的方法来解决这个问题。我需要这样的东西:

let http = require('http'),
    Promise = require('bluebird');

let action = (done) => {
  return new Promise((resolve, reject) => {
    http
      .get('http://domain.com', resolve.bind({}, 'all good!'))
      .on('error', reject.bind({}, 'all wrong!'));
  })
  .then((response) => {
    console.log('Result', response);
    return done(response);  // <----------- I wan't to see this as the response
                            //              of the lambda function
  });
};

module.exports.run = (event, context, cb) => cb(null, action(done));

【问题讨论】:

    标签: ecmascript-6 bluebird aws-lambda aws-api-gateway serverless-framework


    【解决方案1】:

    不,承诺不会那样做。从未来读取是不可能的,也不想(不能)阻止。您的操作仍然是异步的。

    但鉴于您的导出无论如何都需要回调,您可以简单地异步调用它:

    module.exports.run = (event, context, cb) => {
        action().then(res => cb(null, res), err=>cb(err));
    };
    

    当然,如果你只是返回承诺会更好。

    【讨论】:

    • 请给出返回承诺的例子。谢谢
    • @elliotrock module.exports.run = (event, context) =&gt; action();,所以在导入之后你会做run(…).then(…)而不是传递回调
    • 有趣的是,我在处理程序中使用了延迟承诺 return yourPromise.then(nextPromise).then(function(result){ cb(returnHttpFormattedResponse) } })
    • 是的,最好避免这种模式。您的函数的用户希望使用 Promise,而不是回调。
    猜你喜欢
    • 1970-01-01
    • 2019-05-28
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多