axios 如果所有迭代都返回空,则执行某些操作,如果其中一个迭代返回某些操作,则执行其他操作

nwlls2ji  于 2023-10-18  发布在  iOS
关注(0)|答案(4)|浏览(180)

我有一个数组的值,我需要通过这些循环运行一个函数的基础上的值,我从一个文本框。
我的代码:

  1. <label for="truck">Truck:</label>
  2. <input type="text" id="truck" name="truck">
  3. <button type="button" id="myButton">Click Me!</button>
  4. const truckBtn = document.getElementById("myButton");
  5. const truckID = document.getElementById("truck");
  6. truckBtn.addEventListener("click", () => {
  7. let arrs = ["one", "two", "three"];
  8. for (const arr of arrs) {
  9. axiosFunction(arr, truckID.value).then(d=> {
  10. console.log(d.data);
  11. if (d.data.length > 0) {
  12. // do something
  13. } else alert("Not Found");
  14. });
  15. }
  16. });

所以d.data如果truckID.value匹配我需要的,则响应是:

  1. []
  2. []
  3. [{...}]

这就是它进入if语句的时候。
另一种情况是:
如果truckID.value不匹配我需要的响应是:

  1. []
  2. []
  3. []

我的问题是,当我有else,它去其他即使有匹配。当数组的长度大于0且至少有一次迭代时,有没有办法写一个if语句?如果所有迭代都返回长度为0,则执行else?

gopyfrb3

gopyfrb31#

如果您可以重写axiosFunction背后的API,以获取所有三个arr值并返回一个批处理,那么您就不会进行多次往返,这将是理想的。但是假设你不能这样做,并且你可以等待所有的往返返回(否则你不知道它们是否都返回空的),你可以使用Promise.all()来等待,直到它们都被解析。

  1. <label for="truck">Truck:</label>
  2. <input type="text" id="truck" name="truck">
  3. <button type="button" id="myButton">Click Me!</button>
  4. truckBtn.addEventListener("click", () => {
  5. let arrs = ["one", "two", "three"];
  6. Promise.all(arrs.map(arr => axiosFunction(arr, truckID.value)))
  7. .then(results => {
  8. console.log(results.map(d => d.data)); // [[], [], [...]]
  9. const firstValidResult = results.find(d => d.data.length > 0);
  10. if(firstValidResult) {
  11. // do something with firstValidResult.data
  12. } else alert("Not Found");
  13. });
  14. });

这段代码使用find,假设您只需要一个有效的结果。如果可能有几个,你可以调整它使用filter

展开查看全部
bvn4nwqk

bvn4nwqk2#

将回调函数设置为一个pwdc函数,这样就可以使用await。然后,您可以根据任何调用是否返回某些内容来设置一个变量。

  1. truckBtn.addEventListener("click", async() => {
  2. let arrs = ["one", "two", "three"];
  3. let found = false;
  4. for (const arr of arrs) {
  5. let d = await axiosFunction(arr, truckID.value);
  6. console.log(d.data);
  7. if (d.data.length > 0) {
  8. found = true;
  9. // do stuff
  10. }
  11. }
  12. if (!found) {
  13. console.log("Not found!");
  14. }
  15. });
iovurdzv

iovurdzv3#

这也取决于你打算如何在数组中循环-你想:

  • 只对第一场比赛进行操作,或
  • 对每场比赛进行操作

找到匹配项后,可以使用break扩展您的示例:

  1. const truckBtn = document.getElementById("myButton");
  2. const truckID = document.getElementById("truck");
  3. truckBtn.addEventListener("click", () => {
  4. let arrs = ["one", "two", "three"];
  5. for (const arr of arrs) {
  6. axiosFunction(arr, truckID.value).then(d=> {
  7. console.log(d.data);
  8. if (d.data.length > 0) {
  9. // do something
  10. break; // don't perform anymore work once we have any match
  11. } else alert("Not Found");
  12. });
  13. }
  14. });

当找到匹配项时,请注意条件中的break-这将阻止对axiosFunction的任何后续调用,这可能是也可能不是您想要的。
下面是处理调用的几种方法,具体取决于您是要等待每个调用,获取第一个匹配结果,还是使用async / awaitArray.map获取所有匹配结果:

  1. const arrs = ["one", "two", "three"];
  2. // execute axiosFunction calls in sequence, like using a for loop
  3. truckBtn.addEventListener("click", async () => {
  4. const matches = arrs.map(async x => await axiosFunction(x, truckID.value))
  5. .filter(x => x.data.length > 0);
  6. const match = matches.find(Boolean); // get the first truthy result
  7. // do something if match is not null
  8. }
  9. // execute all axiosFunction calls in parallel
  10. truckBtn.addEventListener("click", async () => {
  11. const promises = arrs.map(x => axiosFunction(x, truckID.value));
  12. // get all matches
  13. const matches = await Promise.all(promises)
  14. .filter(x => x.data.length > 0);
  15. const match = matches.find(Boolean); // get the first truthy result
  16. // do something if match is not null
  17. }
  18. // execute axiosFunction calls in parallel, waiting for the first to resolve
  19. truckBtn.addEventListener("click", async () => {
  20. const promises = arrs.map(x => axiosFunction(x, truckID.value));
  21. const firstResolved = await Promise.race(promises);
  22. const match = firstResolved.data.length > 0 ? firstResolved : null;
  23. // do something with match
  24. });
  25. // execute axiosFunction calls in parallel, handling if none of them resolve
  26. truckBtn.addEventListener("click", async () => {
  27. const promises = arrs.map(x => axiosFunction(x, truckID.value));
  28. let match = null;
  29. try {
  30. const firstResolved = await Promise.any(promises);
  31. match = firstResolved.data.length > 0 ? firstResolved : match;
  32. } catch (err) {
  33. // no promise resolved
  34. }
  35. // do something with match
  36. });
展开查看全部
mo49yndu

mo49yndu4#

当您使用axiosFunction发出多个请求时,首先需要使用Promise.allSettled()Promise.all()解析这些promises
然后,您可以使用Array.prototype.some()Array.prototype.every()来检查返回的数据,看起来您需要嵌套其中两个,因为您的结果是一个包含更多数组的数组。
下面是一个模拟axiosFunction的例子。在输入字段中键入foo作为一个结果,或者键入其他内容作为“未找到”:

  1. const searchButton = document.getElementById("searchButton");
  2. const truckInput = document.getElementById("truckInput");
  3. const items = ["one", "two", "three"];
  4. function axiosFunction(array, value) {
  5. return Promise.resolve({
  6. data: value === 'foo' ? array.map((_, i) => [{}]) : array.map(_ => []),
  7. })
  8. }
  9. searchButton.addEventListener("click", async () => {
  10. const { value } = truckInput;
  11. // Make all requests in parallel:
  12. const promises = items.map((item) => {
  13. return axiosFunction(items, value)
  14. })
  15. // Wait for all of them to resolve:
  16. const results = await Promise.allSettled(promises);
  17. // Extract the data part from the results:
  18. const resultsData = results.map(result => result.value.data);
  19. console.log(resultsData);
  20. // Iterate over the data from each request:
  21. const found = resultsData.some((resultData) => {
  22. // Itereate over the array items returned by each request:
  23. return resultData.some((resultItem) => {
  24. // And check if any of them contains something:
  25. return resultItem.length > 0;
  26. });
  27. })
  28. if (found) {
  29. alert("Found!");
  30. } else {
  31. alert("Not Found...");
  32. }
  33. });
  1. <label for="truck">Truck:</label>
  2. <input type="text" id="truckInput">
  3. <button type="button" id="searchButton">Search</button>
展开查看全部

相关问题