未捕获(承诺中)类型错误:X 不是函数
P粉401527045
P粉401527045 2024-03-21 18:13:44
0
1
465

我正在尝试构建一个 vue 应用程序,通过 Spotify 的 API 进行搜索来查找曲目。但我有一个问题,它说:

未捕获(承诺中)类型错误:searchTracks 不是函数

每当我调用 searchTracks 函数时。我寻找解决方案,但似乎找不到。 我有在不同文件 (useSpotify.js) 上访问 Spotify API 的代码(我仍在学习)

import { ref } from 'vue'

const useSpotify = async () => {
    let token
    const id = 'MyId'
    const secretId = 'mySecretId'

    const res = await fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + btoa(id + ':' + secretId)
        },
        body: 'grant_type=client_credentials'
    });

    token = await res.json();
    console.log(token);

    const searchTracks = async (searchTerm) => {
        console.log(token)
        const res = await fetch(`https://api.spotify.com/v1/search?${searchTerm}&type=track`, {
            method: 'GET',
            headers: { 'Authorization': 'Bearer ' + token }
        });
        const data = ref(null)
        data.value = await res.json()
        console.log(data.value)

        return data.value
    }

    return { searchTracks }
}

export default useSpotify

我在 vue 组件中调用它只是为了尝试一下(Login.vue)您可以转到 //searchTry 查看此尝试完成的代码

<template>
  <form @submit.prevent="handleLoginSubmit">
    <h3>Login</h3>
    <input type="email" placeholder="Email" v-model="email" />
    <input type="password" placeholder="Password" v-model="password" />
    <div class="error" v-if="error">{{error}}</div>
    <button v-if="!isPending">Login</button>
    <button v-if="isPending" disabled>Loading..</button>
  </form>
  <input type="text" v-model="searchTerm">
  <button @click="search">search</button>
</template>

<script>
import useLogin from "@/composables/useLogin";
import { ref } from '@vue/reactivity';
import { useRouter } from 'vue-router';
// searchTry
import useSpotify from '../../composables/spotifyApi/useSpotify'
// searchTry
export default {
  setup() {
    const {error, isPending, login} = useLogin()
    const router = useRouter()

    const email = ref('')
    const password = ref('')

    const handleLoginSubmit = async () =>{
      const res = await login(email.value, password.value)
      if(!error.value){
        router.push({name: 'UserPlaylists'})
      }
    }
    // search try
    const searchTerm = ref('')
    const {searchTracks} = useSpotify()
    const search = async () =>{
      const res = searchTracks(searchTerm.value)
    }
    // search try

    return{email, password, isPending, error, handleLoginSubmit, searchTerm, search}
  },
};
</script>

<style>
我不明白问题来自哪里。请帮忙(我仍然不太擅长 JavaScript,请指出我所犯的错误)

P粉401527045
P粉401527045

全部回复(1)
P粉427877676

您将 useSpotify 定义为 async 函数,调用时应使用 awaitthen() 。异步函数的响应始终是承诺。 文档

useSpotify().then((result) => {
        const {searchTracks} = result
        // rest of your code
    })
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板