简体   繁体   中英

Get Promise data out of it Javascript

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM