D
D
DemonIa2018-02-04 19:50:56
JavaScript
DemonIa, 2018-02-04 19:50:56

How to add an element to the array of a variable that is in a Promise?

Hello. I deal with promises, and the question arose: how to rewrite the code below so that the response value from the loop is concatenated in console.log(storage)?
In my code (as it seems to me) there are two problems:
1. Since the storage variable is declared through let, it is visible only in the block in which it is declared.
2. Well, the value in .then cannot be accessed outside of the promise.

let core = require('core');

    let storage = '';
    multipleElements.forEach(function(singleElement){
        core.somePromise(singleElement)
            .then(function(response){
              storage = storage + response;
            })
    });

    console.log(storage)

Can you please tell me how to rewrite it?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Zharov, 2018-02-05
@DemonIa

Promise.all() takes an array of promises and resolves to an array of results

let core = require('core');
    let promises = multipleElements.map(singleElement => core.somePromise(singleElement));
    Promise.all(promises)
        .then(resultArray => console.log(resultArray.join('')))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question