NodeJS:在使用promise时遇到麻烦

时间:2018-08-01 07:56:50

标签: javascript node.js

每次运行此命令时,都会出现错误Error: It broke

为什么这行不通?我觉得一切都做对了,但是错误弹出的时间可能比应该的要快。

const steam = require('steamidconvert')(config.steamapi)
const axios = require('axios');
const jp = require('jsonpath')


var steamid64;
var customid;
var logIds;
var steamid;

var getSteamIDs = new Promise(function(resolve, reject) {
    if (args[0] == "") {
        message.channel.send("Error, you need to enter a link to your steam profile after !me (e.g. !me https://steamcommunity.com/id/ElkYT)")
    } else {
        if (args[0].toLowerCase().indexOf("steamcommunity.com/id".toLowerCase()) != -1) {
            if (args[0].slice(-1) == "/") {
                customid = args[0].slice((args[0].indexOf("d")) + 2, args[0].lastIndexOf(args[0].slice(-1)))
            } else {
                customid = `${args[0].slice((args[0].indexOf("d")) + 2, args[0].lastIndexOf(args[0].slice(-1)))}${args[0].slice(-1)}`
            }
            steam.convertVanity(customid, function (err, res) {
                if (err) {
                    message.channel.send(`ERROR: Couldn't fetch Steam profile!`);
                    console.log(err)
                }
                steamid64 = res
                steamid = steam.convertToText(steamid64)
            })
        } else if (args[0].toLowerCase().indexOf("steamcommunity.com/profiles".toLowerCase()) != -1) {
            if (args[0].slice(-1) == "/") {
                steamid64 = args[0].slice((args[0].indexOf("l")) + 4, args[0].lastIndexOf(args[0].slice(-1)))
                steamid = steam.convertToText(steamid64)
            } else {
                steamid64 = `${args[0].slice((args[0].indexOf("l")) + 4, args[0].lastIndexOf(args[0].slice(-1)))}${args[0].slice(-1)}`
                steamid = steam.convertToText(steamid64)
            }
        }
    }
    if (steamid64) {
        resolve(steamid64);

    } else {
        reject(Error("It broke"))
    }
});

function getLogIDs(steamid64) {
    console.log('steamid64: ',steamid64)
    axios.get('http://logs.tf/json_search?player=' + steamid64 + '&limit=10')
        .then(response => {
            logIds = (jp.query(response.data, '$..logs[*].id'));
        })
        .catch(error => {
            console.log(error);
        });
}

getSteamIDs.then(function(data) {
    getLogIDs(data);
  }).then(function() {
    console.log(logIds);
  });

非常感谢您:)

编辑1:抱歉,将代码更改为我的所有实际代码,而不是简化/示例代码

1 个答案:

答案 0 :(得分:0)

错误消息大概显示为“无法访问then上的属性undefined

这意味着getSteamIDs(steamid64)undefined(即调用该函数的返回值)。关于steamid64,它什么也没说。

getSteamIDs(steamid64) undefined,其功能是:

function getSteamIDs() {
  steamid64 = 1234567890
}

…没有return语句,因此它返回undefined

then()是您在promise上找到的一种方法,甚至没有在getSteamIDs函数内部创建promise。