How To Get Response Synchronously And Request Asynchronously?
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; outArr = []; var fetchData = async (str) => { var b = await fetch('http://api.mathjs.org/v4/?expr=' + str); var c = await b.
Solution 1:
You can't make anything asynchronous synchronous - instead, the best way would be to make abc
async
and await
each iteration. (That's if you don't want to make all requests at once - if you're OK making all requests at once, use Promise.all
instead)
You should also take care not to implicitly create global variables as you're doing with outArr
and len
.
Here's how you would do it with await
:
const fetchData = async (str) => {
const b = awaitfetch('https://api.mathjs.org/v4/?expr=' + str);
return b.json();
}
asyncfunctionabc() {
const output = [];
for (const i ofArray.from({ length: 10 }, (_, i) => i + 1)) {
const str = i + '*' + i;
const result = awaitfetchData(str);
output.push(result);
}
return output;
}
abc()
.then(output => {
console.log(output);
});
(mathjs has a certificate problem, so you may need to add an exception in your browser for the snippet to work)
Solution 2:
Use the index as first parameter. Call fetchData as follows:
fetchData(index, expr);
Within fetchData, fill an array with the result of the api call
outArr[index] = c;
Print the result or outArr!
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const outArr = [];
let count = 0;
const fetchData = async (i, str) => {
var b = awaitfetch("https://api.mathjs.org/v4/?expr=" + str);
var c = await b.json();
outArr[i] = c;
count++
if (count === arr.length) {
console.log(outArr);
}
};
functioncompute(arr) {
len = arr.length;
for (let i = 0; i < len; i++) {
var str = i + "*" + i;
fetchData(i, str);
}
}
compute(arr);
Post a Comment for "How To Get Response Synchronously And Request Asynchronously?"