如何获取异步函数的值并保存它

我是 javascript 新手。我有一个异步函数 getListBar。在 getListBar 中,我使用 getAccount 的返回结果,就像函数 fetch( 你可以看到 user.access_token) 的输入一样。代码运行正确,但我不想每次使用 getListBar 时都调用 getAccount。那么我怎样才能得到 getAccount 的结果并保存它呢?


我尝试了很多方法,但对我来说很难保证,我不知道如何保存它的结果


async function getAccount() {

    try {

        let response = await fetch(apiAuthen,

            {

                method: 'POST',

                headers: {

                    Accept: '*/*',

                    'Authorization': 'Basic a2VwbGxheTpva2Vwba2VwbGxaQ1YWwjJA==',

                    'Content-Type': 'application/x-www-form-urlencoded',

                    'grant_type': 'password',

                },

                body: qs.stringify({

                    'grant_type': 'password',

                    'username': 'abc',

                    'password': 'abc',

                    'client_id': 'abc',

                })

            })

        let responseJson = await response.json();

        return responseJson.data;

    } catch (error) {

        console.log(`Error is : ${error}`);

    }

}

async function getListBar() {

    try {

        const user = await getAccount().then(user => { return user });

        let response = await fetch(apiBar,

            {

                headers: {

                    'Authorization': 'Bearer ' + user.access_token

                }

            })

        let responseJson = await response.json();

        return responseJson.data;

    } catch (error) {

        console.log(`Error is : ${error}`);

    }

}

getAccount 将返回这样的 Promise,我想在其中保存 access_token


Promise {_40: 0, _65: 0, _55: null, _72: null}

_40: 0

_55: {access_token: "41b369f2-c0d4-4190-8f3c-171dfb124844", token_type: "bearer", refresh_token: "55867bba-d728-40fd-bdb9-e8dcd971cb99", expires_in: 7673, scope: "read write"}

_65: 1

_72: null

__proto__: Object


繁花如伊
浏览 227回答 2
2回答

偶然的你

如果不能简单地在定义这些函数的同一范围内存储一个值,我将创建一个Service来处理获取用户。最好在它自己的文件中账户服务.jsclass AccountService {  getAccount = async () => {    if (this.user) {      // if user has been stored in the past lets just return it right away      return this.user;    }    try {      const response = await fetch(apiAuthen, {        method: 'POST',        headers: {          Accept: '*/*',          Authorization: 'Basic a2VwbGxheTpva2Vwba2VwbGxaQ1YWwjJA==',          'Content-Type': 'application/x-www-form-urlencoded',          grant_type: 'password'        },        body: qs.stringify({          grant_type: 'password',          username: 'abc',          password: 'abc',          client_id: 'abc'        })      });      const responseJson = await response.json();      this.user = responseJson.data; // store the user      return this.user;    } catch (error) {      console.log(`Error is : ${error}`);    }    // you should decide how to handle failures    // return undefined;    // throw Error('error getting user :(')  };}// create a single instance of the classexport default new AccountService();并在需要的地方导入import AccountService from './AccountService.js'async function getListBar() {    try {        // use AccountService instead        const user = await AccountService.getAccount().then(user => { return user });        let response = await fetch(apiBar,            {                headers: {                    'Authorization': 'Bearer ' + user.access_token                }            })        let responseJson = await response.json();        return responseJson.data;    } catch (error) {        console.log(`Error is : ${error}`);    }}每次在 getListBar 中您仍然会调用 getAccount 但它只会在 AccountService 没有存储用户时获取

慕姐8265434

现在我以不同的方式写作export default class App extends Component {&nbsp; constructor() {&nbsp; &nbsp; super();&nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; accessToken: '',&nbsp; &nbsp; &nbsp; users: [],&nbsp; &nbsp; &nbsp; listBar: []&nbsp; &nbsp; }&nbsp; }&nbsp; //Get Account&nbsp; Check = () => {&nbsp; &nbsp; getAccount().then((users) => {&nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; users: users,&nbsp; &nbsp; &nbsp; &nbsp; accessToken: users.access_token&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }).catch((error) => {&nbsp; &nbsp; &nbsp; this.setState({ albumsFromServer: [] });&nbsp; &nbsp; });&nbsp; }&nbsp; //Get Account&nbsp; getAccount() {&nbsp; &nbsp; return fetch(apiAuthen,&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; method: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Accept: '*/*',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Authorization': 'Basic a2VwbGxheTpva2Vwba2VwbGxaQ1YWwjJA===',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Content-Type': 'application/x-www-form-urlencoded',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'grant_type': 'password',&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; body: qs.stringify({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'grant_type': 'password',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'username': 'abc',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'password': 'abc',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'client_id': 'abc',&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; }).then((response) => response.json())&nbsp; &nbsp; &nbsp; .then((responseJson) => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; users: responseJson.data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; accessToken: responseJson.data.access_token&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; return responseJson.data&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch((error) => {&nbsp; &nbsp; &nbsp; &nbsp; console.error(error);&nbsp; &nbsp; &nbsp; });&nbsp; }&nbsp; //Get List Bar&nbsp; getListBarFromServer() {&nbsp; &nbsp; return fetch(apiBar, {&nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; 'Authorization': 'Bearer ' + this.state.accessToken&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }).then((response) => response.json())&nbsp; &nbsp; &nbsp; .then((responseJson) => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(this.getListBarFromServer()) <---- Just run if console&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ listBar: responseJson.data });&nbsp; &nbsp; &nbsp; &nbsp; return responseJson.data&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch((error) => {&nbsp; &nbsp; &nbsp; &nbsp; console.error(error);&nbsp; &nbsp; &nbsp; });&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; this.getAccount();&nbsp; &nbsp; this.getListBarFromServer();&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <View style={{ top: 100 }}>&nbsp; &nbsp; &nbsp; &nbsp; <FlatList data={this.state.listBar} renderItem={({ item }) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <View>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Text>{item.bar_id}</Text>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </View>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; }}>&nbsp; &nbsp; &nbsp; &nbsp; </FlatList>&nbsp; &nbsp; &nbsp; </View>&nbsp; &nbsp; )&nbsp; }}它只是在我 console.log(this.getListBarFromServer()) 时运行。请向我解释为什么?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript