繁体   English   中英

如果另一个API没有数据,则仅使用一个API

[英]Using only one API if another one does not have data

const getUser = async (user) => {
    const body = await snekfetch.get('https://www.website.com/api/public/users?name=' + user);
    const userInfo = JSON.parse(body.text);
    const r = await snekfetch.get('https://www.website.com/api/public/users/' + userInfo.uniqueId + '/profile');
    const extraUserInfo = JSON.parse(r.text);
    const _message = await client.users.get('437502925019807744').send({ files: ['https://www.website.nl/avatar-imaging/avatarimage?figure=h' + userInfo.figureString + '.png'] });
    const avatarImage = _message.attachments.first().url;
    return { userInfo, extraUserInfo, avatarImage };
};

getUser(args[0]).then((result) => {
    message.channel.send(`${result.userInfo.name}`);
}).catch(function(result) {
    console.log(result.userInfo.name);
});

在这里,我尝试使用3个API,但是,总会result.userInfo.name ,即使一个存在而其他都不存在,我也尝试仅使用result.userInfo.name仅使用第一个API,在我使用的catch中第一个,然后我尝试了一个仅具有第一个API但没有第二个API的名称,但是我仍然得到: TypeError: Cannot read property 'name' of undefined因为它也会查看第二个API,我还能做什么?处理这种情况? 所以基本上我该如何仅捕获第一个API的错误

编辑:我也尝试过:

    if (extraUserInfo.user.name) {return { userInfo, extraUserInfo, avatarImage };}
    else {return { userInfo, avatarImage };}

尝试修复它

try {
    const r = await snekfetch.get('https://www.website.com/api/public/users/' + userInfo.uniqueId + '/profile');
    const extraUserInfo = JSON.parse(r.text);
    return {
        userInfo,
        extraUserInfo,
        avatarImage
    };
} catch (error) {
    const extraUserInfo = {
        'error': 'not-found'
    };
    return {
        userInfo,
        extraUserInfo,
        avatarImage
    };
}
};
getUser(args[0]).then((result) => {
    console.log(result.extraUserInfo.error === 'not-found' ? result.userInfo.name : result.extraUserInfo.user.name);
}).catch((error) => {
    console.log(error);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM