【问题标题】:Spotify API - Promise stuck on pendingSpotify API - 承诺停留在未决状态
【发布时间】:2022-02-10 05:13:13
【问题描述】:

我是 Javascript 新手,请多多包涵。我正在尝试拼凑一个网站,我可以去该网站查看我当前在 Spotify 上播放的歌曲。它应该每 1000 毫秒通过 fetch 方法向 Spotify API 发出 GET 请求,并在屏幕上更新 SongNameElement 而无需用户刷新。

我使用了this code,我在网上找到了通过可公开访问的 JSON 文件完成自我更新 div。

我还使用this code 来提供请求标头(令牌等)。

可以在here 找到示例 JSON 数据。我需要this的值

Spotify API 返回一个 JSON 文件。到目前为止,我已经设法在 Python 中实现它,因此对 API 的身份验证不是问题。我正在运行一个烧瓶 Python Web 服务器,它返回 JavaScript 和 HTML(参见下面的代码),但是每当它向 API 发出请求时,promise 都会被标记为待处理,但我不确定它为什么没有完成。以下是我的代码:

import spotipy.util as util
from bs4 import BeautifulSoup
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return """
    <div id="SongName">Song Name</div>
    <div id="ArtistName">Artist Name</div>
    <script>
      function updateDataOnScreen() {
        const SongNameElement = document.getElementById("SongName")
        FetchResponse = fetch("https://api.spotify.com/v1/me/player/currently-playing", {
          method: 'GET', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer (my token goes here, but has been redacted)'
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        })
        .then(response => response.json())
        .then(json => SongNameElement.innerHTML = FetchResponse)
        .catch(error => console.error(error));
        console.log(FetchResponse)
      }
      document.addEventListener("DOMContentLoaded", function(event) {
        setInterval(updateDataOnScreen, 1000) // interval value in milliseconds
      })
    </script>
    """

if __name__ == '__main__':
    app.run(debug=True)

开发者工具不断显示this

注意我已经从标题中编辑了我的令牌,所以如果你自己运行它,你需要用你的 Sptify 令牌替换它,你可以得到here

【问题讨论】:

  • 您在创建分配给它的承诺后立即记录FetchResponse(并且您创建一个 new 承诺并每 1000 毫秒记录一次)。为什么不会它总是记录为待处理?
  • 我怀疑您的 真正 问题(因为这很像 XY 问题)是您将 FetchResponse 分配给 innerHTML 而不是 json。 (虽然response.json()返回的解析值是从JSON解析的JS数据结构,而不是JSON本身。所以当你将它强制转换为字符串时,它会变成[object Object]
  • 那么我应该在哪里/应该改变什么来完成承诺,以便我可以获取数据?
  • 使用then() 获取数据(并处理data而不是promise)而不是在promise链之外记录。

标签: javascript html json flask spotify


【解决方案1】:

不确定我做了什么,但它有效。干杯昆汀让我的思绪运转起来!

import requests
from bs4 import BeautifulSoup
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return """
    <div id="SongName">Song Name</div>
    <script>
      function updateDataOnScreen() {
        const SongNameElement = document.getElementById("SongName")
        FetchResponse = fetch("https://api.spotify.com/v1/me/player/currently-playing", {
          method: 'GET', // *GET, POST, PUT, DELETE, etc.
          mode: 'cors', // no-cors, *cors, same-origin
          cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer (AUTHKEY)'
          },
          redirect: 'follow', // manual, *follow, error
          referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        })
        .then(response => response.json())
        .then(response => SongNameElement.innerHTML = (response.item.name))
        .catch(error => console.error(error));
      }
      document.addEventListener("DOMContentLoaded", function(event) {
        setInterval(updateDataOnScreen, 1000) // interval value in milliseconds
      })
    </script>
    """

if __name__ == '__main__':
    app.run(debug=True)

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 1970-01-01
  • 2020-03-16
  • 2019-03-11
  • 2017-09-27
  • 2020-10-22
相关资源
最近更新 更多