使用Promise / Async选择要使用的数据

时间:2018-08-30 17:44:45

标签: javascript promise

我尝试通过以下方式访问datajson值,但是现在只能访问data值,我该怎么做才能访问json值还有吗?

const getUser = user => new Promise(async (resolve, reject) => {
	try {
		const read = await snekfetch.get('https://www.website.nl/api/public/users?name=' + user);
		const data = JSON.parse(read.text);
		const result = await snekfetch.get('https://www.website.com/api/public/users/' + data.uniqueId + '/profile');
		const json = JSON.parse(result.text);
		resolve(data, json);
	} catch (error) {
		reject(error);
	}
});
const promise = Promise.resolve(getUser(args[0]));
promise.then(function(data, json) {
	const name = data.name;
	const motto = data.motto;
	const memberSince = data.memberSince;
	const groups = json.groups.length;
	const badges = json.badges.length;
	const friends = json.friends.length;
	const rooms = json.rooms.length;
	message.channel.send(`${name}\n${motto}\n${memberSince}\n${groups || 'N/A'}\n${badges || 'N/A'}\n${friends || 'N/A'}\n${rooms || 'N/A'}\n`);
}).catch(function(err) {
	console.log(err);
	return message.reply(`${args[0]} does not exists.`);
});

1 个答案:

答案 0 :(得分:0)

当您解决一个承诺时,您将您要解决的数据传递给一个值。如果您要解析多个数据,则将它们粘贴在一个对象中并使用该对象进行解析

const getUser = user => new Promise(async (resolve, reject) => {
  try {
    const read = await snekfetch.get('https://www.website.nl/api/public/users?name=' + user);
    const data = JSON.parse(read.text);
    const result = await snekfetch.get('https://www.website.com/api/public/users/' + data.uniqueId + '/profile');
    const json = JSON.parse(result.text);
    resolve({ data, json }); // <--- created an object with two properties
  } catch (error) {
    reject(error);
  }
});

getUser('someUser')
  .then((result) => {
    console.log(result.data)
    console.log(result.json)
  })

此外,我想指出的是,您在不需要它们的地方创建了额外的承诺。异步函数会自动创建Promise,因此您的getUser函数可以是:

const getUser = async (user) => {
  const read = await snekfetch.get('https://www.website.nl/api/public/users?name=' + user);
  const data = JSON.parse(read.text);
  const result = await snekfetch.get('https://www.website.com/api/public/users/' + data.uniqueId + '/profile');
  const json = JSON.parse(result.text);
  return { data, json };
}