首页 > 解决方案 > 如何在javascript中做顺序承诺?

问题描述

以下是我使用 async await 获取令牌的代码,该令牌用于发出另一个请求。

但问题是,即使我将其作为一个一个异步等待请求进行,在进行第二次异步调用之前也没有定义令牌。

所以我遇到了一个很大的错误。

  try {
    const access = await superagent
      .post("https://token-link.com/token")
      .send(
        "apikey=" + API_KEY
      )
      .set("Content-Type", "application/x-www-form-urlencoded")
      .set("Accept", "application/json");

      const token = access.body["access_token"];

// console.log(token) -- > here I'm doing a console log and I'm being able to see the token.
      

// But when the following request is made right after the above one, I'm getting an error.

    const report = await superagent
      .post(
        "https://another-link/api/v2/data"
      )
      .set("Accept", "application/json")
      .set("Authorization", "Bearer " + token)
      .set("Content-Type", "application/json;charset=UTF-8")
      .send(
       JSON.stringify(data)
      );

    res.send(report);

// also when I do a console.log(report.body.data) --> then also I'm getting an error... 


  } catch (e) {
    res.status(400).json({ error: e });
  }

现在,如果我在发出第二个请求之前执行 curl 请求并将令牌存储为常量,那么错误就消失了。

所以我假设第一个请求在第二个请求完成之前没有完成

有人可以帮忙吗?

  try {
   const token = "eyJraWQiOiIyMDIxMDQyMDE4MzYiLCJhbGciOiJSUzI1NiJ9.eyJpYW1faWQiOiJJQk1pZC01NTAwMDlFUzY5IiwiaWQiOiJJQk1pZC01NTAwMDlFUzY5IiwicmVhbG1pZCI6IklC"
      

// If the token is stored as a constant then there is no error.

    const report = await superagent
      .post(
        "https://another-link/api/v2/data"
      )
      .set("Accept", "application/json")
      .set("Authorization", "Bearer " + token)
      .set("Content-Type", "application/json;charset=UTF-8")
      .send(
       JSON.stringify(data)
      );

    res.send(report);
  } catch (e) {
    res.status(400).json({ error: e });
  }

我的异步等待是按预期工作还是我错过了什么?

标签: javascript

解决方案


如果您无法从评论中弄清楚(但您的代码应该可以正常工作),要回答您的问题,您有 2 个选择:

  1. 在第一个承诺中,然后调用第二个(在您的代码上工作正常,但不能扩展)
  2. 使用 async.waterfall

推荐阅读