我是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
发布于 2019-10-08 22:02:30
您需要在AllUsersReducer中使用async/await
const AllUsersReducer = async () => {
const fetchData = await GetDataFromFetch()
console.log('My Data', fetchData);
return fetchData
}; GetDataFromFetch是异步的,这意味着它的结果将是一个Promise。要从该Promise获得结果,您需要使用await。
https://stackoverflow.com/questions/58287647
复制相似问题