简体   繁体   English

这是处理 JavaScript promise 的正确方法吗?

[英]Is this the correct way to deal with a JavaScript promise?

Forgive me but I am new to JS promises.请原谅我,但我对 JS 承诺不熟悉。 I think I need to use one for interacting with an AWS service, which writes to and pulls data from DynamoDB.我认为我需要使用一个与 AWS 服务交互,该服务从 DynamoDB 写入和提取数据。 I have a JavaScript app which is ran by the Serverless npm plugin, which defines exported functions as end points.我有一个 JavaScript 应用程序,它由无服务器 npm 插件运行,它将导出的函数定义为端点。 In these endpoints after the promise has completed I need to bubble the data back up to the endpoint to expose it as a JSON body.在 promise 完成后的这些端点中,我需要将数据冒泡备份到端点以将其公开为 JSON 主体。 See the code below.请参阅下面的代码。

exports.getBlog = async (event) => {
    return getBlogPost(event).then((data) => {
        console.log("worked", data);
        var response =  {
            statusCode: 200,
            body: JSON.stringify(data)
        };

        return response;
    })
    .catch((error) => {
        console.log("didn't work");
        var response = {
            statusCode: 400,
            body: JSON.stringify(error.toString())
        };

        return response;
    });
}

What makes me think it's not right is that I have to create a var response and return it, and then return again outside of that in the root of exports.getBlog .让我觉得不正确的是我必须创建一个var response并返回它,然后在exports.getBlog的根目录之外再次返回。 Is this right?这是正确的吗? It makes the JSON print correctly, but am confused from reading tutorials online as to whether this is good practice?它使 JSON 打印正确,但是从在线阅读教程中对于这是否是好的做法感到困惑?

If not, how would you return data from the promise and expose it as a JSON result?如果不是,您将如何从 promise 返回数据并将其公开为 JSON 结果?

In this example, exports.getBlog is referenced by the Serverless framework as an endpoint, like so:-在此示例中, exports.getBlog被无服务器框架引用为端点,如下所示:-

functions:
  get-blog:
    handler: api/blog.getBlog
    events:
      - http:
          path: api/v1/blog
          method: GET
          cors: true

You are mixing the two.你正在混合两者。 Here is with async/await这是异步/等待

 exports.getBlog = async (event) => {
 try {
    var res = await getBlogPost(event);
    var data = res.data;
    console.log("worked", data);
    var response =  {
        statusCode: 200,
        body: JSON.stringify(data)
    };

    return response;
} catch(error) {
    console.log("didn't work");
    var response = {
        statusCode: 400,
        body: JSON.stringify(error.toString())
    };

    return response;
   }
}

and without并且没有

exports.getBlog = event => {
    return getBlogPost(event).then((data) => {
    console.log("worked", data);
    var response =  {
        statusCode: 200,
        body: JSON.stringify(data)
    };

    return response;
})
.catch((error) => {
    console.log("didn't work");
    var response = {
        statusCode: 400,
        body: JSON.stringify(error.toString())
    };

    return response;
});
}

Good read: https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9好读: https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9

EDIT: adding MDN's article on async/await and how one can rewrite promise code with it编辑:添加MDN 关于 async/await 的文章以及如何用它重写 promise 代码

There are two main methods to write promise first using resolve and reject functions and second using.then and.catch function.编写 promise 有两种主要方法,首先使用解析和拒绝函数,其次使用.then 和.catch function。

First case example:第一个案例示例:

let promise = new Promise(function(resolve, reject) {
  setTimeout(() => reject(new Error("Whoops!")), 1000);
});

// reject runs the second function in .then
promise.then(
  result => alert(result), // doesn't run
  error => alert(error) // shows "Error: Whoops!" after 1 second
);

Second case example:第二种情况示例:

If we're interested only in successful completions, then we can provide only one function argument to.then:如果我们只对成功完成感兴趣,那么我们可以只提供一个 function 参数给.then:

let promise = new Promise(resolve => {
  setTimeout(() => resolve("done!"), 1000);
});

promise.then(alert); // shows "done!" after 1 second

If we're interested only in errors, then we can use null as the first argument: .then(null, errorHandlingFunction).如果我们只对错误感兴趣,那么我们可以使用 null 作为第一个参数:.then(null, errorHandlingFunction)。 Or we can use.catch(errorHandlingFunction), which is exactly the same:或者我们可以使用.catch(errorHandlingFunction),完全一样:

let promise = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error("Whoops!")), 1000);
});

// .catch(f) is the same as promise.then(null, f)
promise.catch(alert); // shows "Error: Whoops!" after 1 second

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM