是否可以在新承诺中添加Await?
最初,我在向服务器发出任何请求之前都不需要等待,但是有一天,服务器要求每个请求在发出之前都要有一个令牌。
让我们以代码为例
export const countries = (data: IData) => {
const countryRequests = getRequests(data)
const countryResponse = countryRequests?.reduce((countryResponse, request) => {
const countryResponses = new Promise((resolve, reject) => {
instance
.post(`/country`, request)
.then(data => {
resolve(data)
})
.catch(err => {
reject(err)
})
})
return [...countryResponse, countryResponses]
}, [])
return countryResponse
}
新代码(将async放入promise的回调中):
export const countries = (data: IData) => {
const countryRequests = getRequests(data)
const countryResponse = countryRequests?.reduce((countryResponse, request) => {
const countryResponses = new Promise(async (resolve, reject) => { //add async here
await addAccessToken() // add header into token before sending the requests
instance
.post(`/country`, request)
.then(data => {
resolve(data)
})
.catch(err => {
reject(err)
})
})
return [...countryResponse, countryResponses]
}, [])
return countryResponse
}
addToken函数:
export const addAccessToken = async () => {
const accessToken = await instance.get<IAccessToken>(
'/access_token'
)
const { access_token } = accessToken.data
instance.defaults.headers.common['Authorization'] = `Be ${access_token}`
}
但是我在下面看到了一个错误
- 承诺执行器函数不应是异步的。(no-async-promise-executor)**
如何消 debugging 误?
export const countries = async (data: IData) => {
const countryRequests = getRequests(data)
await addAccessToken()
const countryResponse = countryRequests?.reduce((countryResponse, request) => {
const countryResponses = instance
.post(`/country`, request) //------- May I ask, if it is successful call, then this will autmactically equvlanet to calling resolve (data) in my previosu code?
.catch(err => {
console.error(err)
})
return [...countryResponse, countryResponses]
}, [])
return countryResponse
}
添加了新的prmosie.所有部件
const countryResponses = countries(data)
//set content for api 1
Promise.all([...countryResponses])
.then(values => {
const countryResponsesResult = values.map((value, _index) => {
return value.data.result ? value.data.result : []
})
//Set content for api 1
props.setProjection({
kind: 'success',
payload: {
data: countryResponsesResult,
},
})
})
.catch(_error => {
//Set content for api 1
props.setProjection({
kind: 'fail',
payload: {
error: new Error(_error.message),
},
})
})
2条答案
按热度按时间wlsrxk511#
正如@deceze提到的,示例已经为你返回了一个承诺,所以不需要返回你自己的承诺。
只是
如果你不想使用
await
,而使用promises和then
,你应该有类似下面的东西(promises chaining):vmdwslir2#
不知怎的我找到了这份工作。