Я пытаюсь извлечь несколько строк из Cosmos DB, а затем сопоставить их, чтобы отобразить компонент для каждого. Вся документация, которую я могу найти для API Azure Cosmos DB, записывает строки в консоль одну за другой, но я не могу найти ни одной, а затем рассказывает вам, как вернуть всю строку.
Я новичок в этом, поэтому, вероятно, делаю это ужасно неправильно, но теперь я застрял и не могу двигаться дальше. Надеюсь, вы сможете помочь...
В моем App.js у меня есть это
function App() {
const [newMembers, setNewMembers] = useState(dataFetch());
В моем dataFetch.js у меня есть
export default async function dataFetch() {
const { endpoint, key, databaseId, containerId } = config;
const client = new CosmosClient({ endpoint, key });
const database = client.database(databaseId);
const container = database.container(containerId);
// Make sure Tasks database is already setup. If not, create it.
// await dbContext.create(client, databaseId, containerId);
try {
console.info(`Querying container: Items`);
// query to return all items
const querySpec = {
query: "SELECT * from c",
};
// read all items in the Items container
const { resources: items } = await container.items
.query(querySpec)
.fetchAll();
return items;
} catch (err) {
console.info(err.message);
}
}
Когда я console.info возвращаю результат, он говорит
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(3)
0: {id: '154', forename: 'Fred', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
1: {id: '416', forename: 'Lee', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
2: {id: '900', forename: 'Kathryn', surname: 'Robson', address1: 'Some address', address2: 'Kingsmead', …}
length: 3
[[Prototype]]: Array(0)
Я видел кое-что в другом месте об использовании .then, но когда я попытался
const { resources: items } = await container.items
.query(querySpec)
.fetchAll()
.then(() => {
return items;
});
Он сказал: «dataFetch.js: 33 не может получить доступ к« элементам »до инициализации».



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


То, что вы делаете в первых двух блоках кода, совершенно нормально. Однако, помещая результат dataFetch() в состояние newMembers, вы просто сохраняете обещание, которое просто разрешается в какой-то момент, и вы можете получить результаты в любой момент с помощью newMembers.then(actualResult => ...).
Однако я думаю, что вы бы предпочли сохранить фактический массив членов в состоянии newMembers. Это можно сделать, например:
function App() {
const [newMembers, setNewMembers] = useState([]); // initially set to an empty array
useEffect(() => {
dataFetch().then(members => setMembers(members));
}, []); // providing an empty array means: run this effect only once when this component is created.
// do something with the newMembers. Initially, it will be []
// but as soon as the data is retrieved from the DB, the actual data will be
// in the state and the component will be rerendered.
}