从多个代码位置调用可选的 JS fetch Promise

问题描述 投票:0回答:1

我需要在代码中访问三个 URL。前两个总是会被访问,但第三个可能会被访问零次、一次或两次。由于所有 URL 都需要大量处理,如果不需要,我不想访问第三个。

我的代码是这样的:

fetch('a').then(result => {
  if (result == '1') {
    fetch('c').then(result => console.log('through a', result));
  }
}
fetch('b').then(result => {
  if (result == '1') {
    fetch('c').then(result => console.log('through b', result));
  }
}

因此,URL“c”的结果可能需要零次、一次或两次。 a、b 和 c 都需要一段时间来处理,因此“a”或“b”可能首先访问“c”。如果两者都需要返回“c”,我不希望执行第二次获取,我希望第二次获取已由第一个获取的值。

我的想法是这样做:

const c = () => {
  return new Promise(() => {
    fetch('c');
  })
}

fetch('a').then(result => {
  if (result == '1') {
    c().then(result => console.log('through a', result));
  }
}
fetch('b').then(result => {
  if (result == '1') {
    c().then(result => console.log('through b', result));
  }
}

但是如果“a”和“b”都返回“1”,这仍然会导致“c”被访问两次。

我该怎么做?

javascript fetch-api es6-promise
1个回答
0
投票

使用

Promise.all()
检查两次获取的结果,如果其中任何一个返回值 1,则从
c
获取。

Promise.all([
    fetch('a').then(res => res.text()), 
    fetch('b').then(res => res.text())]).then((result1, result2) => {
        if (result1 == "1" || result2 == "1") {
            fetch('c').then(...)
    });
© www.soinside.com 2019 - 2024. All rights reserved.