簡體   English   中英

從 promise (RIOT API) 獲取請求數據

[英]Get request data from a promise (RIOT API)

我有一個來自 NodeJs 的“請求”請求,我想用 promise 獲取數據。 一切都很好,因為控制台向我顯示了我被請求的信息。 問題是當我調用 promise function 時,控制台會顯示這個。 我怎樣才能得到真正的價值?

let leagueTier = (accId) => new Promise(async (resolve, reject) => {
            request({
                url: `https://${reg}.api.riotgames.com/lol/league/v4/entries/by-summoner/${accId}${key}`,
                json: true
            }, (error, response, body) => {
                if (!error && response.statusCode === 200) {
                    resolve(body[0].tier.toLowerCase())
                } else {
                    reject(Error('It broke'))
                }
            })
        }).then(function(res) {
            return res;
        })

這就是我稱之為 function 的地方

.attachFiles([`./images/${leagueTier(body.id)}.png`])

(node:5868) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat 'D:\Dev\shen-bot\images[object Promise].png'

如何訪問我提出的請求的字符串? 也許我不應該使用承諾?

leagueTier返回值將是一個 promise,最終解析或拒絕為一個值。 您不能簡單地將返回值添加為字符串的一部分。 您可以使用awaitthen等待值通過。

// asuming you are in async function context
.attachFiles([`./images/${await leagueTier(body.id)}.png`]);

// or
leagueTier(body.id).then(tier => {
  .attachFiles([`./images/${tier}.png`]);
});

請注意,您當前的代碼:

.then(function(res) {
  return res;
})

絕對什么都不做,可以省略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM