Superagent vs Fetch 返回承诺——如何处理这些?

Superagent & Fetch returning promises -- How to handlle these?

请原谅这个问题,对于更有经验的 JS 程序员来说,这个问题可能很容易解决。我一直在阅读 superagent 和 fetch,试图让 REST 调用正常工作。 (我能够让 odata 正常工作,但我现在需要 REST)。但是,我对承诺感到困惑。我目前正在尝试使用以下代码制作一个简单的 request.get(或 fetch.get):

this.ticketList = Request.get(url).then((response) => {
    return response.body.Tickets;
});
console.log(this.ticketList); // Returns a promise..?

我对 promise 不熟悉,也不知道如何处理。我读过的所有文档都说异步调用是一件好事,但我的应用程序是线性的,在继续之前需要来自上一次调用的数据。我不需要承诺,我需要完整的回应。 (我对promises/ajax的有限理解有误请指正!)

如何更改上面的代码来给我想要的响应对象? (JSON 首选)或者,我如何处理获取所需数据的承诺?

谢谢, 查理

您需要将需要数据的调用包装在 then 语句中。不幸的是,大多数 HTTP 请求都是异步的,如果不进行一些认真的修补,您将无能为力(这是不值得的)。

如果您必须将 promise 中的值返回给另一个函数,您最好返回 promise 本身并在它解决后在那里处理它。

基于您提供的代码的示例:

function shareTickets() {
  // Get the promise to resolve
  var getTicketPromise = getTickets();

  // Resolve the promise and handle as needed
  getTicketPromise
    .then((ticketData) => {
      console.log('I got the data from the promise: ' + ticketData);
      doSomethingWithData(ticketData);
    })
    // If an error happens, you can catch it here
    .catch((error) => console.log(error));
}

// Return the promise itself so it can be resolved in the other function.
function getTicketPromise() {

  // Just return the promise
  return Request.get(url);
}

刚开始学习如何处理 promise 时会有点痛苦,但它们的回报是巨大的。只要坚持练习一段时间,最终你就会掌握它。

基本上,有了 promises,您可以通过将 then 链接在一起来处理这个问题。

Request.get(url)
       .then((response) => {
           return response.body.Tickets;
        })
       .then((ticketList) => {
           console.log(ticketList);
        });

在这种特定情况下,将其分成两个 then 而不是直接使用 response.body.Tickets 确实没有任何好处。通常,您会在这里执行所有操作,直到需要进行异步调用的下一点为止,然后您会得到一个新的承诺。例如:

Request.get(url)
       .then((response) => {
           var ticketList = response.body.Tickets;
           console.log(ticketList);
           return Request.get(url2);
        })
       .then((response2) => {
           /* ... */
        });

本质上,如果您有一组线性操作,一旦您进行第一次异步调用,该调用之后的所有操作都会在 then 语句(或 catch 语句来处理被拒绝的承诺)。