简体   繁体   中英

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?

 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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