简体   繁体   English

如何从承诺返回两个结果

[英]how to return two results from promise

I am using fetch to get data from two different api:s.我正在使用 fetch 从两个不同的 api:s 获取数据。 I need to use both of the api data in the same function.我需要在同一个函数中使用这两个 api 数据。 One is finished much faster than the other, so to make this work I have used promise.all.一个完成得比另一个快得多,所以为了完成这项工作,我使用了 promise.all。 But now I am stuck with two questions.但现在我被两个问题困住了。

  1. How can I return 2 results (test1 and test2) to the next promise?如何将 2 个结果(test1 和 test2)返回到下一个承诺? Right now my code stops and says that "test1 is not defined".现在我的代码停止并说“test1 未定义”。

  2. If I use promise.all and then run .json on each file (like the code below), will the code wait for each json to finish before returning the result?如果我使用 promise.all 然后在每个文件上运行 .json(如下面的代码),代码是否会在返回结果之前等待每个 json 完成? Or may one not finish?或者一个可能没有完成?

code:代码:

Promise.all([fetch1, fetch2])
    .then((file) => {
      let test1 = file[0].json()
      let test2 = file[1].json()
      return ([test1, test2])
    }).then((data) => {
      console.log(test1)
      console.log(test2)
    })

You can return a Promise.all on both .json calls inside the .then :您可以返回一个Promise.all上都.json内部通话.then

Promise.all([fetch1, fetch2])
    .then((file) => {
      let test1 = file[0].json()
      let test2 = file[1].json()
      return Promise.all([test1, test2])
    }).then(([test1, test2]) => {
      console.log(test1)
      console.log(test2)
    })

But it would probably be better to take both fetch requests and .map them to their .json() Promises, then call Promise.all on the result:但是最好同时接受fetch请求并将它们.map到他们的Promise.all .json() Promises,然后在结果上调用Promise.all

const getApi = url => fetch(url).then(res => res.json());
Promise.all([
  getApi('url1'),
  getApi('url2')
])
  .then(([test1, test2]) => {
    // do stuff with test1 and test2
  })
  .catch((err) => {
    // handle errors
  });

The above code will result in the requests being processed in parallel;上面的代码会导致请求被并行处理; neither request will prevent the other request from continuing.这两个请求都不会阻止另一个请求继续。 In contrast, your (tweaked) original code will require the response headers from both requests to be received and processed before the .json() (to process the body) for either can start.相比之下,您的(调整后的)原始代码将需要在.json() (处理正文)开始之前接收和处理来自两个请求的响应标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM