无法从承诺到减速器获得价值

时间:2019-10-08 13:44:38

标签: reactjs mongodb promise async-await reducers

我是Promises和Async / Await的新手,我想从mongoDB获取一系列用户,但是当我得到它时,我就收到了它的承诺,并且想在我的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

1 个答案:

答案 0 :(得分:0)

您需要在async中使用await / AllUsersReducer

const AllUsersReducer = async () => {
    const fetchData = await GetDataFromFetch()
    console.log('My Data', fetchData);
    return fetchData
}; 

GetDataFromFetch是异步的,这意味着结果将是Promise。要从该Promise获得结果,您需要使用await

相关问题