简体   繁体   English

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

[英]Choose which data to use using promise/async

I tried the below to acces both data and json values, however I can now only acces the data values, what can I do to acces the json values as well? 我在下面尝试了访问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.`); }); 

when you resolve a promise, you pass in a single value with the data you want to resolve it to. 兑现承诺时,您将您要兑现的数据传递给单个值。 If there are multiple pieces of data you want to resolve with, then stick them in an object and resolve with that object 如果要解析多个数据,则将它们粘贴在一个对象中并使用该对象进行解析

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)
  })

Additionally, i want to point out that you're creating extra promises where they are not needed. 另外,我想指出的是,您在不需要它们的地方创建了额外的承诺。 async functions automatically create promises, so your getUser function can just be: 异步函数会自动创建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 };
}

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

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