【问题标题】:How to use .then for async functions如何将 .then 用于异步函数
【发布时间】:2020-07-22 22:03:52
【问题描述】:

所以我试图链接来自 api 的请求,我知道这是一个异步请求。然而,我的理解是,使用.then() 会返回一个承诺,并且代码会等待它被解决,然后再转到下一个.then()。当我console.log变量encryptedAccountId而不是返回它时,我得到了想要的结果。但是当我尝试将其放入下一个 url 时,它说变量未定义。我也尝试过使用awaitasync,但没有成功。我在这里想念什么?

let summonerName = 'nightblue3';
const region = ['na1', 'br1', 'eun1', 'euw1', 'jp1', 'kr', 'la1', 'la2', 'oc1', 'ru', 'tr1'];
let endIndex = 100;
let beginIndex = 0;
const fetch = require("node-fetch");

  let userUrl = `https://${region[0]}.api.riotgames.com/lol/summoner/v4/summoners/by-name/${summonerName}?api_key=${apiKey}`
  fetch(userUrl).then(res => {
        return res.json()})
        .then(getEncryptedAcccountId=> {
        var encryptedAccountId = (getEncryptedAcccountId.accountId)
        return encryptedAccountId})
        .then(fetch(`https://${region[0]}.api.riotgames.com/lol/match/v4/matchlists/by-account/${encryptedAccountId}?endIndex=${endIndex}&beginIndex=${beginIndex}&api_key=${apiKey}`))```

【问题讨论】:

  • .then(fetch()) 应该是then(encryptedAccountId => fetch())
  • @VLAZ 你真的是一个圣人先生。上帝保佑你。

标签: javascript node.js api asynchronous callback


【解决方案1】:

你可以写得更简单:

fetch(userUrl).then(res => res.json())
   .then(({ accountId }) => fetch(`your_url_with_${accountId}`))

【讨论】:

  • 别忘了catch
【解决方案2】:

您传递给then() 的函数确实不会被调用,直到调用了promise then 解决。

.then(fetch(`https://${region[...

问题是您没有将函数传递给then。您正在立即调用fetch() 并传递它的返回值(这是一个承诺,而不是一个函数)。

改为传递函数:

.then((encryptedAccountId) => fetch(`https://${region[...

您可能还想转至async/await syntax,这通常更具可读性:

(async function () {
  let summonerName = "nightblue3";
  const region = ['na1', 'br1', 'eun1', 'euw1', 'jp1', 'kr', 'la1', 'la2', 'oc1', 'ru', 'tr1'];
  let endIndex = 100;
  let beginIndex = 0;
  const fetch = require("node-fetch");

  let userUrl = `https://${region[0]}.api.riotgames.com/lol/summoner/v4/summoners/by-name/${summonerName}?api_key=${apiKey}`;
  const userResponse = await fetch(userUrl);
  const userData = await userResponse.json();
  const encryptedAccountId = userData.accountId;
  const matchlists = await fetch(
    `https://${region[0]}.api.riotgames.com/lol/match/v4/matchlists/by-account/${encryptedAccountId}?endIndex=${endIndex}&beginIndex=${beginIndex}&api_key=${apiKey}`
  );
  // ...
})();

【讨论】:

  • 谢谢,但是当我将console.log(encryptedAccountId) 放入异步中时,一切都会运行,但我无法对变量进行视觉验证。
  • 我完全不知道你所说的“对变量进行视觉验证”是什么意思
  • 我只想控制台记录数据,这样我就可以准确地看到我在拉什么
  • 我如何console.log( encryptedAccountId) 才能清楚
猜你喜欢
  • 2016-09-06
  • 2017-07-20
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 2018-05-06
  • 2020-03-09
  • 1970-01-01
相关资源
最近更新 更多