即使使用 Await,Promise 仍会返回 Undefined

Promise keeps returning Undefined even using Await

我是 Node.Js 的新手,我正在尝试为我的 WhatsApp 群组制作一个集成了 Spotify 的聊天机器人(我正在使用 wa-automate 和 spotify-web-api -node),我为每个命令创建了一个服务层,并创建了一个 Spotify 存储库来搜索专辑、曲目等,但是当我尝试读取 albumList 时,getAlbumByName returns 它总是未定义,即使它有效当我在 SpotifyRepository 中用 console.log() 打印它时就好了,我已经尝试过的事情:

我怀疑在中间件中验证 SpotifyWebApi 或我围绕层组织的整个思考过程可能是问题所在。

这是我的代码:

const SpotifyRepository = require('../repositories/spotifyRepository.js');

module.exports = class command {
    constructor() {
      this.name = 'getAlbum';
      this.aliases = ['getAlbum'];
      this.description = '>getAlbum';
      this.spotifyRepository = new SpotifyRepository();
    }
    
    async run(client, message, args) {
      let albumName = args.split(' - ')[0];
      let artistName = args.split(' - ')[1];
      let albumList = await this.spotifyRepository.getAlbumByName(albumName, artistName);
      client.sendText(message.from, albumList.items[0]);
    }

};

var SpotifyWebApi = require('spotify-web-api-node');

class SpotifyRepository {
    constructor() {
        this.spotifyApi = new SpotifyWebApi({
            clientId: '*************************',
            clientSecret: '*************************'
        });
        const handler = {
            get: function (obj, prop) {
              return typeof obj[prop] !== "function"
                ? obj[prop]
                : async function (...args) {
                    await obj.checkAuth(prop);
                    obj[prop].apply(obj, args);
                  };
            },
          };
        return new Proxy(this, handler);
    };

    async checkAuth(){
        let token = await this.spotifyApi.clientCredentialsGrant();
        this.spotifyApi.setAccessToken(token.body['access_token'])
    };

    async getAlbumByName(albumName, artistName) {
        return await this.spotifyApi.searchAlbums(albumName + ' artist:' + artistName);
    }
};

module.exports = SpotifyRepository;

感谢您的帮助! (很抱歉,如果这让人难以阅读,英语不是我的母语)

async function (...args) {
  await obj.checkAuth(prop);
  obj[prop].apply(obj, args);
};

在代理内部,您正在做的是让任何试图访问某个函数的人都获得这个函数。但是这个函数没有 return 语句,所以它隐含地 returning 一个解析为 undefined 的承诺。你应该添加一个 return 语句,它转发任何真正的函数 returns:

async function (...args) {
  await obj.checkAuth(prop);
  return obj[prop].apply(obj, args);
};