【发布时间】:2021-10-22 02:06:46
【问题描述】:
我有一个这样的课程(简化):
export class Foo {
constructor(el, menuItems ) {
this.id = this.el.dataset.id;
this.menuItems = menuItems;
this.fetchResult = async function (uri) {
fetch(uri, {
method: 'get'
})
.then(response => response.json())
.then(data => {
return data.saved === true;
})
.catch(function (err) {
console.log('Failed ', err);
return false;
});
}
}
doAction(action) {
const uri = 'foo/'+ action +'?id=' + this.id;
const map = {
'close': async () => {
const success = await this.fetchResult(action);
console.log(success); // says undefined?
}
/* some other actions */
}
return map[action];
}
attachDialogs() {
this.menuItems.addEventListener('click', (element) => {
this.doAction( element.dataset.action )();
});
}
}
由于某种原因,const success = await this.fetchResult(action); 不等待结果。它立即继续,产生“未定义”值。
在后台进行提取。如何让它等待结果?
【问题讨论】:
-
尝试使您的 doAction 函数异步,然后在 eventListener 中使用 await 调用它?您的“doAction”函数返回一个异步但函数本身不是异步的函数
-
你永远不会从
fetchResult返回任何东西。您可能还打算将uri传递给fetchResult,而不是action。 Many dupes.
标签: javascript ecmascript-6 async-await