Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question