gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:13:44 25 4
gpt4 key购买 nike

我是 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

最佳答案

如果不能简单地将值存储在定义这些函数的相同范围内,我会创建一个 Service 来处理获取用户。最好在自己的文件中

AccountService.js

class 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 class
export 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 未存储用户时获取。

关于javascript - 如何获取异步函数的值并保存它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com