如何将.then用于异步功能

问题描述 投票:0回答:2

因此,我尝试链接来自api的请求,并且我知道这是一个异步请求。但是据我的理解,使用.then()会返回一个承诺,并且代码会在继续下一个.then()之前等待其解决。当我console.log变量encryptedAccountId而不返回它时,我得到了期望的结果。但是,当我尝试将其放入下一个网址时,它表示变量未定义。我也尝试使用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}`))```
javascript node.js api asynchronous callback
2个回答
0
投票

您可以写得更容易:

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

0
投票

实际上,传递给then()的函数只有在解决方案上调用promise then时才会被调用。

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

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

改为传递函数:

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


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

async

© www.soinside.com 2019 - 2024. All rights reserved.