【发布时间】:2020-02-11 08:38:38
【问题描述】:
我很难对 API 调用进行排序。所以我使用 then() 链接按顺序排列它们。所有 API 和刷新令牌都是 Promises/Async。它正在工作,但是是否有更清洁/更漂亮/更短的方法而不使用异步/等待,因为我的父函数不是异步的。我不完全理解 .then() 和 async/await 的行为
这是父函数内部的代码:
refreshToken().then(token => {
let request = {} //format request
return axios.post(`${youtubeUrl}/upload/youtube/v3/videos?access_token=${token}&part=contentDetails`, request) //upload video
})
.then(uploadResponse => {
let uploadResponse = {}; //format uploadResponse
refreshToken().then(token => { //refresh the token again
return axios.put(`${youtubeUrl}?access_token=${token}`, uploadResponse) //update existing video
})
.then(updateResponse => {
let updateResponse = {}; //format updateResponse
axios.post(`${BasePath}/v1/videos`, updateResponse, headers)
.then(postResponse => {
if (postResponse.data.response === 'success') {
return dispatch(receivePostsData(postResponse.data))
} else if (postResponse.data.response === 'failed') return dispatch(receivePostsData(postResponse.data))
})
})
})
.catch(error => {
return dispatch(receivePostsData(error))
})
【问题讨论】:
-
你能不能用扁平化的方式使用你所有的
.thens?doThis().then().then().then().then()等。这就是 Promises 的全部内容。 -
Promise 是可链接的
-
@VLAZ:嵌套使用闭包,所以不能完全展平,虽然可以移除一些嵌套,全局可以完全展平。
-
使用
return更多。 -
@Makopa 通过将您的逻辑步骤包装成几个函数,一些 destructoring 和隐式返回,.then 链可以写成 7 行易于阅读的行,例如 this
标签: javascript node.js reactjs ecmascript-6