0
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?

2
  • 3
    let arr = []; const example = str => { arr.push(str) }; Don't call the var e - most everybody use that for event like we use i for index Commented Nov 5, 2021 at 13:50
  • 2
    There is. Just push to an array, and then you can concat the array when you see fit. Commented Nov 5, 2021 at 13:50

3 Answers 3

1
let arr = [];
const example = e => {
  arr.push(e);
  console.log(e);
};
Sign up to request clarification or add additional context in comments.

Comments

0

Just declare somewhere an array and push the values there.

let arr = [];
const example = item => {
        arr.push(item);
        console.log(arr);
    };

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.