So I am trying to chain request from an api and I am aware of that this is an asynchronous request. However it is my understanding that using .then()
returns a promise, and that the code waits for it to be resolved before moving on to the next .then()
. When I console.log
the variable encryptedAccountId
instead of returning it, I get the desired result. But when I try to put that into the next url, it says the variable is undefined. I have also trying using await
and async
but to no luck. What am I missing here?
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}`))```
You could write it easier:
fetch(userUrl).then(res => res.json())
.then(({ accountId }) => fetch(`your_url_with_${accountId}`))
The function you pass to then()
will, indeed, not be called until the promise then
is called on resolves.
.then(fetch(`https://${region[...
The problem is that you are not passing a function to then
. You are immediately calling fetch()
and passing its return value (which is a promise, not a function).
Pass a function instead:
.then((encryptedAccountId) => fetch(`https://${region[...
You might also like to move to async
/ await
syntax which is generally more readable:
(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}`
);
// ...
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.