axios 如何在Promise中添加等待?

8fq7wneg  于 2022-11-29  发布在  iOS
关注(0)|答案(2)|浏览(163)

是否可以在新承诺中添加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),
          },
        })
      })
wlsrxk51

wlsrxk511#

正如@deceze提到的,示例已经为你返回了一个承诺,所以不需要返回你自己的承诺。
只是

export const countries = async (data: IData) => {

await addAccessToken()
const countryResponses = await instance.post(`/country`, request)
//your code//

如果你不想使用await,而使用promises和then,你应该有类似下面的东西(promises chaining):

export const countries = (data: IData) => {

addAccessToken()
     .then((data)=>{
        const countryResponses = instance.post(`/country`, 
        request)
     })
     .then(//your code//)
vmdwslir

vmdwslir2#

不知怎的我找到了这份工作。

export const countries = (data: IData)=> {
  const countryRequests  = getRequests(data)
  const countryResponse  = countryRequests?.reduce((countryResponse, request) => {
    // return promise
    const countryResponses  = new Promise((resolve, reject) => {
      addAccessToken().then(()=>{
        instance
          .post(`/country`, request)
          .then(data => {
            // change the returned propmise state into resolved
            resolve(data)
          })
          .catch(err => {
            reject(err)
          })
      })

    })
  //return the whole set of simlationCalls promise. When all promise is resolved, promise all will be notified and excute whatever it needs to execute
    return [...countryResponse, countryResponses]
  }, [])

  return countryResponse
}

相关问题