ошибка «что-то пошло не так» при функции getfloat

#javascript

#javascript

Вопрос:

Этот код отлично работает рядом с последней частью, и я не вижу, где может быть ошибка. Я протестировал это, и основная проблема заключается в Trade.prototype.getFloat, возможно, это идентификатор обратного вызова (Trade.prototype.getFloat я получил его из 3y сообщения здесь, в stack от другого пользователя).

3y проблема: этот код отлично работает, кроме этой строки: «inventory[asset.assetid].floatvalue = getFloat». Как вы можете видеть, он находится в асинхронном режиме, и эта строка инициализирует запрос на получение некоторого значения, но он не может его получить, потому что значение не определено. Я протестировал это и основную проблему в запросе, который тоже является асинхронным. Итак, ответ заключается в том, как остановить асинхронный режим и дождаться возврата запроса.

 'use strict'

const config = require('../config')
const request = require('request')
const async = require('async')
const Trade = require('./index')

const MAX_RETRIES = 3
const API_URL = 'https://api.steamapis.com/steam/inventory'

Trade.prototype.getInventory = function getInventory(steamID64, appID, contextID, callback, retries) {
    request(`${API_URL}/${steamID64}/${appID}/${contextID}?api_key=${config.SteamApisKey}`, (error, response, body) => {
        if (!error amp;amp; response.statusCode === 200) {
            const items = JSON.parse(body)
            const assets = items.assets
            const descriptions = items.descriptions

            const inventory = {}

            if (descriptions amp;amp; assets) {
                async.forEach(descriptions, (description, cbDesc) => async.forEach(assets, (asset, cbAsset) => {
                    if (
                        description.classid !== asset.classid ||
                        !description.tradable || 
                        !description.marketable ||
                        description.market_hash_name.indexOf('Souvenir') > -1
                    ) {
                    return cbAsset()
                    }

                    if (typeof inventory[asset.assetid] !== 'undefined') {
                    return cbAsset()
                    }

                    const type = Trade.prototype.getItemType(description.market_hash_name, description.type)
                    const wear = Trade.prototype.getItemWear(description.market_hash_name)
                    const inspect = Trade.prototype.getInspect(steamID64, asset.assetid, description.actions)
                    const getFloat = Trade.prototype.getFloat(inspect, asset.assetid, function(_float){
                    var data = String(_float);
                    inventory[asset.assetid].floatvalue = data;
                    inventory[asset.assetid] = asset
                    inventory[asset.assetid].item_type = type
                    inventory[asset.assetid].item_wear = wear
                    inventory[asset.assetid].inspect = inspect
                    inventory[asset.assetid].data = {
                        background: description.background_color,
                        image: description.icon_url,
                        tradable: description.tradable,
                        marketable: description.marketable,
                        market_hash_name: description.market_hash_name,
                        type: description.type,
                        color: description.name_color,
                    };
                    return cbAsset();
                })
                }));
            }
            return callback(null, inventory)
        }
        let retry = retries
        if (typeof retries === 'undefined') {
            retry = 0
        }
        retry  = 1
        if (retry <= MAX_RETRIES) {
            return Trade.prototype.getInventory(steamID64, appID, contextID, callback, retry)
        }
        let statusCode = null
        if (typeof response !== 'undefined' amp;amp; typeof response.statusCode !== 'undefined') {
            statusCode = response.statusCode
        }
        return callback({ error, statusCode })
    })
}

Trade.prototype.getInventories = function getInventories(params, callback) {
    const inventories = {}
    async.each(params, (user, cb) => {
        Trade.prototype.getInventory(user.steamID64, user.appID, user.contextID, (err, data) => {
            inventories[user.id] = {}
            inventories[user.id] = {
                error: err,
                items: (!err) ? Object.keys(data).map(key => data[key]) : null,
            }
            cb()
        })
    }, () => {
        callback(inventories)
    })
}

Trade.prototype.getItemType = function getItemType(marketHashName, type) {
    if (marketHashName.indexOf('Key') !== -1) {
        return { value: 0, name: 'key' }
    }
    if (marketHashName.indexOf('★') !== -1) {
        return { value: 1, name: 'knife' }
    }
    if (
        type.indexOf('Classified') !== -1 ||
        type.indexOf('Contraband') !== -1 ||
        type.indexOf('Covert') !== -1
    ) {
        return { value: 2, name: 'rare_skin' }
    }
    if (
        type.indexOf('Consumer Grade') !== -1 ||
        type.indexOf('Base Grade') !== -1 ||
        type.indexOf('Graffiti') !== -1 ||
        type.indexOf('Sticker') !== -1 ||
        type.indexOf('Industrial Grade') !== -1
    ) {
        return { value: 4, name: 'misc' }
    }
    return { value: 3, name: 'weapon' }
}

Trade.prototype.getItemWear = function getItemWear(marketHashName) {
    if (marketHashName.indexOf('Factory New') !== -1) {
        return 'FN'
    }
    if (marketHashName.indexOf('Minimal Wear') !== -1) {
        return 'MW'
    }
    if (marketHashName.indexOf('Field-Tested') !== -1) {
        return 'FT'
    }
    if (marketHashName.indexOf('Well-Worn') !== -1) {
        return 'WW'
    }
    if (marketHashName.indexOf('Battle-Scarred') !== -1) {
        return 'BS'
    }
    return false
}
Trade.prototype.getInspect = function getInspect (steamID64, assetid, actions) {
    let inspectLink = null;                                           
    if (actions) {
        for (const a in actions) {
            if (actions[a].name.indexOf('Inspect') !== -1) {
                   inspectLink = actions[a].link
                   inspectLink = inspectLink.replace('%owner_steamid%', steamID64)
                   inspectLink = inspectLink.replace('%assetid%', assetid)
            }
        }
    }
    return inspectLink
}

Trade.prototype.getFloat = function getFloat (adding, callback) {
    request ("https://api.csgofloat.com:1738/?url="   adding, (error, response, body) => {

     if (!error amp;amp; response.statusCode == 200) {
         var floatBody = JSON.parse(body);
         var float = floatBody["iteminfo"]["floatvalue"];
         var id = id;
         if (float != "") {
             callback(float);
         } else {
             return "wrong";
         }
     } else {
        console.log('something goes wrong');
        return "wrong";
    }
    });
}

  

Комментарии:

1. how to stop the async mode and wait the return of the request вы не можете

2. посмотрите, как вы callback(float); … ну callback(null); или что-то в этом роде — вместо return "wrong") on an error, and in the callback check for null`

3. кроме того, внутренняя Trade.prototype.getInventory функция… вы не вызываете Trade.prototype.getItemType(...) etc, просто используйте this.getItemType(...)

4. вот так: `if (float != «») {обратный вызов (float); } else {обратный вызов (ошибка); } } else {console.log(‘что-то пошло не так’); возвращает «неправильно»; } }); }`

5. конечно, но как насчет последнего условия else — для которого требуется обратный вызов (ошибка) — и `callback (error), куда вы его помещаете, будет обратный вызов с null или undefined или что-то еще falsey, поскольку в этом случае это явно falsey