我正在尝试做这样的事情,但是很麻烦:
myAsyncFunction = async () => {
fetchResource().then( res => {
await fetchAnotherResource()
....
})
}
在完成第一个承诺的过程中,我想使用await表达式,但这看起来不像该回调的范围允许异步功能。
通过上面的方法,它告诉我await是一个保留关键字(在这种情况下,由于我猜测的范围,它对await没有任何意义?)
如果我使用async
声明匿名函数,如下所示:
fetchResource().then( async (res) => {...})
我收到这样的语法错误:
ProductForm.jsx?130a:143 Uncaught (in promise) TypeError: (0 , _context.t1) is not a function
我不确定是否相关,但这在React组件内部。
有没有一种语法可以完成我在这里要做的事情? (使用异步函数作为Promise处理程序)
编辑:相关代码(抱歉,代码转储)
initializeState = async () => {
getShopInfo(this.state.shop_id)
.then (async (res) => {
if (product_id) {
({ activeLocalization, localizations } = await this.initializeEditState(product_id, defaultLocalization, localizations))
} else {
({ activeLocalization, localizations } = await this.initializeBlankState(defaultLocalization, localizations))
}
})
}
initializeEditState = (product_id, defaultLocalization, localizations, allCategoriesPromises) => {
return new Promise( resolve => {
let productPromiseArray = []; // storage for auxiliary localization requests
let filledOutLocalizations = []; // hold localizations that have been merged with the product data
getProduct(product_id, defaultLocalization.localization_id)
.then( json => {
/* fetch object that will represent a product in state
* and merge it with the default localization object */
let defaultProductState = this.setupEditProductState(json)
defaultLocalization = Object.assign(defaultLocalization, defaultProductState)
/* setup promise array for all other localizations */
localizations.forEach( l => {
productPromiseArray.push(getProduct(product_id, l.localization_id))
})
/* fetch other products and merge them with localizations */
Promise.all( productPromiseArray )
.then( resultArray => {
resultArray.forEach( res => {
/* test for fail condition here;
* fail condition happens when new localizations
* are registered between edits */
let loc = localizations.find(
l => l.localization_id == res.data.product.localization_id
)
if (res.result) {
loc = Object.assign(loc, this.setupEditProductState(res))
} else {
/* Default state for this localization
* (you should have access to defaultLocalization) */
loc = Object.assign(defaultProductState, loc)
}
filledOutLocalizations.push(loc)
})
/* Finally, get ALL category lists and
* INITIALIZE EDIT STATE */
let promiseArray = []
for (var filLoc of filledOutLocalizations) {
promiseArray.push(getAllCategories(filLoc.localization_id))
}
resolve({ activeLocalization: defaultLocalization, localizations: filledOutLocalizations })
})
})
})
}
initializeBlankState = ( defaultLocalization, localizations ) => {
return new Promise( resolve => {
let activeLocalization = Object.assign(
defaultLocalization,
this.getBlankState(defaultLocalization.localization_id)
)
activeLocalization.product.enable_flg = 1
localizations = localizations.map( l => {
return Object.assign(l, this.getBlankState(l.localization_id))
})
resolve({ activeLocalization, localizations })
})
}
答案 0 :(得分:2)
该代码在您的原始版本中不起作用,因为await
仅可在async
函数内使用。 then
内部的函数有其自己的范围,该范围不再与外部的函数相关;因此使用await
无效。
第二个版本中,您将async
放在then
内是违反返回类型的。来自Promise.prototype.then
的{{3}}:
then()方法返回一个Promise
和async function
中的MDN definition:
异步函数声明定义了一个异步函数,该函数 返回一个AsyncFunction对象
您会发现这两个不应同时使用。
通常,async-await
用于替换Promise - then - catch
,而不是一起使用。因此,对于您的示例函数,应为:
myAsyncFunction = async () => {
const resource = await fetchResource();
if (isValidResource(resource)) {
const anotherResource = await fetchAnotherResource();
...
}
}
对于您使用initializeState
的函数async
:
initializeState = async () => {
const res = await getShopInfo(this.state.shop_id);
if (product_id) {
({ activeLocalization, localizations } = await this.initializeEditState(product_id, defaultLocalization, localizations))
} else {
({ activeLocalization, localizations } = await this.initializeBlankState(defaultLocalization, localizations))
}
}
答案 1 :(得分:1)
根据我的观点,在您的情况下,async
中的then(..)
是多余的。只需继续使用Promises。在fetchResource().then( res => fetchAnotherResource()).then(res=>{code...})
中,最后一个代码将等待fetchAnotherResource(..)
完成。
因此,您的代码
.then (async (res) => {
if (product_id) {
({ activeLocalization, localizations } = await this.initializeEditState(product_id, defaultLocalization, localizations))
} else {
({ activeLocalization, localizations } = await this.initializeBlankState(defaultLocalization, localizations))
}
})
可以像
一样重写.then ((res) => product_id?
this.initializeEditState(product_id, defaultLocalization, localizations)):
this.initializeBlankState(defaultLocalization, localizations))
)
.then(({activeLocalization,localizations})=>{.....})