-1

I try this:

var result = [];
promise.then(function (data) {
  result.push(data);

});
console.log(result)

and the result array is empty. Is there a way to get it out of the promise?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
mk2015
  • 205
  • 2
  • 14

2 Answers2

1

No, you can't.

The point of promises is to allow a simple chaining of actions, some of them asynchronous.

You may do

var result = [];
promise.then(function (data) {
    result.push(data);
}).then(function(){
    console.log(result)
});

I'd suggest you to read this introduction to promises.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Promises are sometimes referred to as futures or future values. You can't directly get the value out of the promise but you can get a promise of a future value, as seen below.

var futureResult = promise.then(function (data) {
    var result = [];
    result.push(data);
    return result;
});

futureResult.then(function (result) {
    console.log(result);
});

futureResult.then(function (result) {
    console.log('another logger');
    console.log(result);
});
anddoutoi
  • 9,973
  • 4
  • 29
  • 28