1

Returning the values inside Promise.all

Hi I am writing a function to load the values from the three promises into an array but I cant seem to work around getting the values from outside the promise.

Need the values field from the callback.

Has anyone found a way to work through this.

var firstPromise = s3.getObject({Bucket: bucket, Key: key1}).promise()
    .then(function(data){
        return data;
    })
    .catch(function(err) {
        console.log(err);
    });
var secondPromise = s3.getObject({Bucket: bucket, Key: key2}).promise()
    .then(function(data){
        return data;
    })
    .catch(function(err) {
        console.log(err);
    });
var thirdPromise = s3.getObject({Bucket: bucket, Key: key3}).promise()
    .then(function(data){
        return data;
    })
    .catch(function(err) {
        console.log(err);
    });

Promise.all([firstPromise, secondPromise, thirdPromise])
    .then(function(values){
        logger.debug("Value 0 is " + values[0].Body.toString());
        logger.debug("Value 1 is " + values[1].Body.toString());

        callback(null,values);
    });
Alvaro Castro
  • 811
  • 1
  • 9
  • 26
igaldb
  • 11
  • 1
  • 3
    What is the problem with `callback(null, values)`? It has the correct `values`, right? – trincot Jul 18 '18 at 20:41
  • Yes the values contains the correct value. I am unable to use it outside the Promise. The callback does not seem to return a value outside the promise. – igaldb Jul 18 '18 at 20:44
  • 2
    Calling a callback is a completely different concept than returning a value, but trying to return a value which you only get in the future is of course not possible. By the time you get the value, the original function has long returned *synchronously*. You need to embrace an asynchronous programming style instead of hoping get synchronous results. So stick with promises all the way. – trincot Jul 18 '18 at 20:48
  • You use the `values` INSIDE the `.then()` handler or you call some function and pass it to that function. Those are your two choices. That's it. You are likely trying to assign it to some other variable and use it there. Can't do that. – jfriend00 Jul 19 '18 at 00:01

0 Answers0