如何使用回调 return unicode 响应

How to return unicode response using callback

我一直无法将 API 的查询结果检索回变量。我正在尝试使用回调函数,但它没有按预期工作。

我的问题是我从 API 得到了响应,当我登录时我可以看到它输出到控制台,但它仍然没有被设置为变量,导致变量未定义。

这是进行查询的函数及其相应的回调函数

function getResult(result)
{
    let gameInfo = result;
    //console.log(gameInfo); /// When uncommented, the response can be seen here, so I know my callback is getting the result.
    return gameInfo;
}
function queryRAWGDatabase(callback,title)
{
    title = title.split(' ').join('-');
    var req = unirest("GET", "https://rawg-video-games-database.p.rapidapi.com/games/" + title);

    req.headers({
        "x-rapidapi-key": process.env.RAWG_GAME_DATABASE_KEY,
        "x-rapidapi-host": "rawg-video-games-database.p.rapidapi.com",
        "useQueryString": true
    });
    req.end(function (result) {
        if (result.error)
        {
            return null;
        };
        return callback(result.body);
    });
}

这里是我调用函数并尝试将其设置为变量的地方。

async function embedBuilder(message)
{
    await message.author.send("Lets get to work!\nPlease enter the title of your event. (Must be shorter than 200 characters)");
    const title = await collector(message,200);
    message.author.send("Please enter the name of the game. (Must be shorter than 200 characters)\nEnter \"None\" if this event does not have a game. ");
    const game_title = await collector(message,200,true);
    let game = queryRAWGDatabase(getResult,game_title); ////////////// CALL MADE HERE /////////
    message.author.send("Please enter a short description of your event. (Must be shorter than 2000 characters)\nEnter \"None\" if no. ");
    const description = await collector(message,2000,true);
    console.log(game); //// When I print it here, I get undefined!
    if (description != null)
    {
        var eventEmbed = new Discord.MessageEmbed()
        .setColor('RANDOM')
        .setTitle(title)
        .setAuthor(message.author.username)
        .setDescription(description)
        .addField("Participants", "None")
        .addField("Not Attending", "None")
        .addField("Tentative", "None")
        .setImage(game.background_image);
    }
    else // Build embed without description
    {
        var eventEmbed = new Discord.MessageEmbed()
        .setColor('RANDOM')
        .setTitle(title)
        .setAuthor(message.author.username)
        .addField("Participants", "None")
        .addField("Not Attending", "None")
        .addField("Tentative", "None")
        .setImage(game.background_image);
    }
/// . . .

最后,这是我的错误。

(node:22974) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'background_image' of undefined
    at embedBuilder (/home/caleb/Programming/PlannerBot/commands/plan.js:80:24)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:22974) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:22974) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

首先,你需要awaitqueryRAWGDatabase函数:

let game = await queryRAWGDatabase(game_title)

You don't need to have a callback if you await, so I removed getResult

但是,目前此功能不可等待。为了解决这个问题,我们需要编辑该函数,使其成为 return 一个 return Promise 实例。它接受带有 resolvereject 参数的回调。您可以调用 resolve 来解决承诺:

function queryRAWGDatabase(title) {
    return new Promise((resolve, reject) => {
        title = title.split(' ').join('-');
        var req = unirest("GET", "https://rawg-video-games-database.p.rapidapi.com/games/" + title);

        req.headers({
            "x-rapidapi-key": process.env.RAWG_GAME_DATABASE_KEY,
            "x-rapidapi-host": "rawg-video-games-database.p.rapidapi.com",
            "useQueryString": true
        });
        req.end(function (result) {
            if (result.error) {
                reject('Error: ' + result.error);
                return;
            };
            resolve(result.body);
        });
    })
}

Instead of the callback, you need to call resolve. Regarding result.error, you can call reject, and then you will get an exception when awaiting.