繁体   English   中英

如何将.then 用于异步函数

[英]How to use .then for async functions

所以我试图链接来自 api 的请求,我知道这是一个异步请求。 但是,据我了解,使用 .then .then()会返回 promise,并且代码会等待它解决后再继续下一个.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}`))```

你可以写得更简单:

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

您传递给then()的 function 实际上不会被调用,直到 promise then被调用解决。

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

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

通过 function 代替:

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

您可能还想改用通常更具可读性的async / await语法

(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}`
  );
  // ...
})();

暂无
暂无

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

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