节点JS与wordnik API请求异步

时间:2018-06-02 05:17:42

标签: javascript node.js api get discord.js

我正在为Discord编写一个简单的机器人,其中在通道中输入命令如下:

“!define apple”

将返回单词的定义(在本例中为apple)。

问题是函数async run()在函数调用wordDef甚至返回定义(来自wordnik API调用)之前完成。

const commando = require('discord.js-commando');
var request = require('request');

function wordDef(word) {
    let url = "https://api.wordnik.com/v4/word.json/" + word + "/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=APIKEY";
        console.log(word);
        console.log(url);

        request.get(url, function(error, response, body) { 
            var str = JSON.parse(body);

            return str[0].text;
        });
}

接下来是:

async run(message, args) {
        if(args[1] != null) {
            var firstWord = args.replace(/ .*/,'');
            console.log("the first word is: " + firstWord);
            message.reply(wordDef(firstWord));

        }
        else {
            message.reply("word please");
        }
    }

我认为这对你们大多数人来说都是一个微不足道的问题,但是如果你能帮助我指出正确的轨道,我将不胜感激!

请在下方找到您的代码的更新版本

"use strict";
const commando = require('discord.js-commando');
let request = require('request'); 
let util = require('util');
let reqGet = util.promisify(request.get); //prosimify get method for async/await**

let wordDef = async (word) => {
    try {
        let url = "https://api.wordnik.com/v4/word.json/" + word + "/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=APIKEY";
        console.log(word);
        console.log(url);

        let str = await reqGet(url); //promsified so sholud work fine
        str = JSON.parse(body);
        return str[0].text;

    } catch (error) {
        throw new Error(error)
    }
}


let run = async (message, args) => {
    try {
        if (args[1] != null) {
            let firstWord = args.replace(/ .*/, '');
            console.log("the first word is: " + firstWord); //`enter code here`
            message.reply(await wordDef(firstWord));

        } else {
            message.reply("word please");
        }
    } catch (error) {
        throw new Error(error)
    }
}

0 个答案:

没有答案