0

I have a function foo() that executes an asynchronous request. This returns an AWS.Request that I can return and handle by the calling function. This will give me access to "data" received by the callback of the AWS.Request. What I want to do is be able for the caller to receive some other value, dependent on the value of "data":

function foo() {
    var user_request = awsrequest({'param1':val1, 'param2': val2}, 
                                   function(err, data) {
                                      if (data == condition) {
                                         return newVal;
                                      } else {
                                         return null;
                                      }
                                  });
    return user_request;
}

The caller works like so:

var request = foo();
request.then(function(result) {
    console.log("result is:");
    console.log(result);
}

"result" here is the value of "data" in the callback function in foo(), returned by the AWS request. I'd like to have the value of "result" be either newVal or null and available when the callback in foo() completes.

How can I do that?

1 Answers1

0

The answer was, as Roamer-1888 said, to follow the answer in converting an existing callback API to promises, and I solved it like this:

function foo() {
    return new Promise(function(resolve, reject) {
                        awsrequest({'param1':val1, 'param2': val2}, 
                                   function(err, data) {
                                      var result = null;
                                      if (data == condition) {
                                         result = newVal;
                                      } 
                                      resolve(result);
                                  })
                         });
}