【发布时间】:2021-08-24 17:39:25
【问题描述】:
我试图了解 promises 和 async await 是如何工作的。我有三个实现,想知道它们是否等效,或者发生的事情是否存在重大差异:
原始实现:
function sendData(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
console.log(key,value)
bodyFormData.append(key,value)
}
axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response){
console.log(response.data)
// do stuff with the data
})
.catch(function(response){
console.log(response)
// do stuff with the error
})
}
第二次实施:
async function sendData2(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
//console.log(key,value)
bodyFormData.append(key,value)
}
try{
const response = await axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
return response.data
}catch(e){
const error =['FATAL ERROR: See Admin', e]
return error
}
}
第三个实现:
function sendData3(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
//console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function(response){
return response.data
})
.catch(function(response){
return response
})
}
【问题讨论】:
-
sendData()的第一个样本没有return,所以它总是返回`undefined。 -
我更新了问题,我在原来的实现中犯了一个错误。确实在原始文件中没有返回,但我们只是将代码移动到使用数据执行的操作中。
标签: javascript async-await promise axios