【发布时间】:2020-02-05 19:36:48
【问题描述】:
我是 Promises 和 Async/Await 的新手,我想从 mongoDB 获取一组用户,但是当我得到它时,我将它作为一个 Promise 接收,并且我想在我的 reducer 中使用它。 我怎样才能做到这一点。 这是我的代码:
import {combineReducers} from 'redux'
import {stitchClient} from '../pages/const'
import {RemoteMongoClient} from 'mongodb-stitch-browser-sdk';
import {DataBase} from '../pages/const';
const mongodb = stitchClient.getServiceClient(
RemoteMongoClient.factory,
"mongodb-atlas"
);
const db=mongodb.db(DataBase);
const collection= db.collection('User');
async function fetch(){
return (
collection.find().toArray()
.then(items => {
console.log(`Successfully found ${items.length} documents.`);
localStorage.setItem('DataTable',JSON.stringify(items));
return items;
})
.catch(err => console.error(`Failed to find documents: ${err}`))
)
}
async function GetDataFromFetch(){
return await fetch();
}
const AllUsersReducer=()=>{
console.log('My Data',GetDataFromFetch());
return (GetDataFromFetch())
};
export default combineReducers({
AllUsers:AllUsersReducer,
});
这是日志: Console Log
【问题讨论】:
-
return await fetch()? -
谢谢,可以使用
return await fetch(),我会编辑代码。
标签: reactjs mongodb promise async-await reducers