首页 > 解决方案 > 函数中包含 return 语句时,数组中的对象为空

问题描述

我有一个要返回对象数组的函数parsedContacts。使用 return 语句,console.log上面它会打印一个空对象数组。当我删除 return 语句时,每个对象都具有预期的三个属性。

如何返回parsedContacts并包含属性?

/* eslint-disable no-console */
/* eslint-disable no-unused-vars */
import { PermissionsAndroid } from 'react-native';
import Contacts from 'react-native-contacts';

export const getAndProcessPhoneContacts = async () => {
  PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
    {
      'title': 'Contacts',
      'message': 'Xxxxxxxx would like to view your contacts.'
    }
  )
  const contacts = await getContacts();
  const parsedContacts = parseContacts(contacts);
  sortContacts(parsedContacts);
  console.log(parsedContacts);
  return parsedContacts; // this line needs to be removed for parsedContacts to have properties in the objects inside it.
}

const getContacts = () => {
  return new Promise((resolve, reject) => {
    Contacts.getAll((error, contacts) => {
      contacts ? resolve(contacts) : reject(error)
    })
  })
}

const parseContacts = contacts => {
  return contacts.map(contact => {
    let parsedContact = {}
    Object.keys(contact).forEach(key => {
      switch (key) {
        case 'givenName':
          parsedContact.firstName = contact[key]
          break
        case 'familyName':
          parsedContact.surname = contact[key]
          break
        case 'phoneNumbers':
          parsedContact.phoneNumber = contact[key].length ? contact[key][0].number : ''
      }
    })
    return parsedContact
  })
}

const sortContacts = contacts => {
  contacts.sort((a, b) => {
    let contactA = a.firstName;
    let contactB = b.firstName;
    return (contactA < contactB) ? -1 : (contactA > contactB) ? 1 : 0;
  });
}

更新

根据下面评论中的要求,这里是getAndProcessPhoneContacts. 我知道这很丑陋,需要重构,对此的任何建议也很感激!

  async componentDidMount() {
    ConnectyCube.init(...config)
    try {
      const accessToken = await getFirebaseToken();
      if (accessToken) {
        await authorizeConnectyCube(accessToken);
        if (this.props.user.parsedContacts) {
          const registeredUsers = await retrieveRegisteredUsers();
          this.props.updateRegisteredContacts(registeredUsers);
          Actions.Dashboard();
        } else {
          const parsedContacts = await getParsedContactsFromStorage();
          if (parsedContacts) {
            this.props.updateParsedContacts(parsedContacts);
            Actions.Dashboard();
          } else {
            const parsedContacts = await getAndProcessPhoneContacts();
            console.log(parsedContacts); // prints an array of empty objects
            await writeParsedContactsToStorage(parsedContacts);
            this.props.updateParsedContacts(parsedContacts);
            const registeredUsers = await retrieveRegisteredUsers();
            this.props.updateRegisteredContacts(registeredUsers);
            Actions.Dashboard();
          }
        }
      } else {
        Actions.PhoneNumberInput();
      }
    } catch (error) {
      Alert.alert(error);
    }
  }  

更新 2

我使用回调有一个不优雅的解决方案:

            const cb = (ct) => {
              console.log(ct); // Objects now have properties
            }
            const parsedContacts = await getAndProcessPhoneContacts(cb);
            await writeParsedContactsToStorage(parsedContacts);
            this.props.updateParsedContacts(parsedContacts);
            const registeredUsers = await retrieveRegisteredUsers();
            this.props.updateRegisteredContacts(registeredUsers);
            Actions.Dashboard();
          }
        }
      } else {
        Actions.PhoneNumberInput();
      }
    } catch (error) {
      Alert.alert(error);
    }
  }

和被调用的函数:

export const getAndProcessPhoneContacts = async (cb) => {
  PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
    {
      'title': 'Contacts',
      'message': 'Xxxxxxx would like to view your contacts.'
    }
  )
  const contacts = await getContacts();
  const parsedContacts = parseContacts(contacts);
  sortContacts(parsedContacts);
  console.log(parsedContacts);
  cb(parsedContacts)
}

标签: javascriptreactjsreact-native

解决方案


推荐阅读