Return value from callback function in AWS Javascript SDK

落花浮王杯 提交于 2020-01-22 03:36:27

问题


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);
  }
});

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?

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.


回答1:


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");


来源:https://stackoverflow.com/questions/54539168/return-value-from-callback-function-in-aws-javascript-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!