从AWS Javascript SDK中的回调函数返回值 [英] Return value from callback function in AWS Javascript SDK

查看:100
本文介绍了从AWS Javascript SDK中的回调函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AWS Javascript SDK,并且正在遵循有关如何发送SQS消息的教程。我基本上遵循的是 AWS教程,其中包含 sendMessage 的示例,如下所示:

I'm using the AWS Javascript SDK and I'm following the tutorial on how to send an SQS message. I'm basically following the AWS tutorial which has an example of the sendMessage as follows:

sqs.sendMessage(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.MessageId);
  }
});

所以 sendMessage 函数使用回调函数输出操作是否成功。而不是打印到控制台,我想返回一个变量,但是我设置的每个值仅在回​​调函数中可见,即使 window.result 之类的全局变量在外部也不可见回调函数。有什么办法可以在回调之外返回值?

So the sendMessage function uses a callback function to output whether the operation was successful or not. Instead of printing to the console I want to return a variable, but every value I set is only visible within the callback function, even global variables like window.result are not visible outside the callback function. Is there any way to return values outside the callback?

我目前发现的唯一解决方法是在HTML元素中设置数据属性,但我认为这不是一个很好的解决方案。

The only workaround I've found at the moment is to set a data attribute in an HTML element, but I don't think it's really elegant solution.

推荐答案

我建议使用 Promise 和新的 ES2016中的async await 关键字。

I would suggest to use Promises and the new async and await keywords in ES2016. It makes your code so much easier to read.

async function sendMessage(message) {

    return new Promise((resolve, reject) => {

        // TODO be sure SQS client is initialized
        // TODO set your params correctly 
        const params = {
            payload : message
        };

        sqs.sendMessage(params, (err, data) => {
            if (err) {
                console.log("Error when calling SQS");
                console.log(err, err.stack); // an error occurred
                reject(err);
            } else {
                resolve(data);
            }
        });         
    });
}

// calling the above and getting the result is now as simple as :
const result = await sendMessage("Hello World");

这篇关于从AWS Javascript SDK中的回调函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆