const example = e => {
console.log(e);
};
Each time an API call is made, example()
or rather e
gives back different strings, such as:
string one
string two
string three
Is there a way to concat all these strings into one array?
CodePudding user response:
let arr = [];
const example = e => {
arr.push(e);
console.log(e);
};
CodePudding user response:
Just declare somewhere an array and push the values there.
let arr = [];
const example = item => {
arr.push(item);
console.log(arr);
};
CodePudding user response:
First of all I would recommend to use a function that sends your requests, e.g. sendRequest()
. If you access a database or some website you have to declare an async
function, because it's unsure, when you get your response back. Your sendRequest
function can then return a javascript object either if the api call was successful or not. The keyword await
waits, until the promise is resolved.
Now to your question: If your call was successful, just push your result to an outer defined array apiResults
, thats it.
const apiResults = [];
async function sendRequest() {
try {
const apiResult = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
const apiSuccess = Boolean(apiResult);
if (apiSuccess) {
apiResults.push(apiResult);
}
return { ok: apiSuccess, data: apiResult };
} catch (err) {
return { ok: false, data: {} };
}
}
(async function test() {
console.log('Before', apiResults);
const response = await sendRequest();
console.log('After', apiResults);
})();
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>