尝试在forEach
export let appState = observable({
bunny : []
});
appState.loadBunny = async function(bugs) {
bugs.forEach(function(data) {
let temp = {};
temp['id'] = data.id;
temp['site_url'] = data.site_url;
temp['email'] = await decrypt(sessionStorage.getItem('key'), data.email);
temp['username'] = await decrypt(sessionStorage.getItem('key'), data.username);
temp['password'] = await decrypt(sessionStorage.getItem('key'), data.password);
temp['note'] = await decrypt(sessionStorage.getItem('key'), data.note);
temp['tag'] = await decrypt(sessionStorage.getItem('key'), data.tag);
temp['created_at'] = data.created_at;
temp['updated_at'] = data.updated_at;
runInAction("update state after decrypting data", () => {
this.bunny.push(temp);
});
});
};
appState.fetch = async function() {
let xoxo = await axios.get('/api/vault/', {
headers: {'Authorization': "JWT " + sessionStorage.getItem('token')}
});
this.loadBunny(xoxo.data);
}
这是错误:
ERROR in ./static/apps/store/passwords.js
Module build failed: SyntaxError: ...static/apps/store/passwords.js: Unexpected token (15:30)
13 | temp['id'] = data.id;
14 | temp['site_url'] = data.site_url;
> 15 | temp['email'] = await decrypt(sessionStorage.getItem('key'), data.email);
| ^
16 | temp['username'] = await decrypt(sessionStorage.getItem('key'), data.username);
答案 0 :(得分:4)
await
应该在async
函数中使用,它用于forEach
回调,这是常规函数。
即使async
函数作为forEach
回调提供,也无法获取承诺,因为forEach
不返回任何内容。
为此,应手动形成承诺链。
appState.loadBunny = async function(bugs) {
let promise = Promise.resolve();
bugs.forEach(function(data) {
promise = promise.then(async function () {
let temp = {};
...
});
});
await promise;
}
这就是for...of
函数中async
必不可少的原因:
appState.loadBunny = async function(bugs) {
for (const data of bugs) {
let temp = {};
...
});
}
在这种情况下,生成器函数和yield
的行为类似。
答案 1 :(得分:3)
return (dynamic)this;
仅适用于await
函数,如下所示:
async
因此,您应该重构代码,以便这些async function test() {
await myObj.setObj(2, 3);
console.log(obj.a + obj.b);
}
test();
调用位于他们自己的await decrypt(sessionStorage.getItem('key'), data.email
函数中。