异步等待不起作用-JavaScript
我正在使用Cloudinary上传图像,然后从Cloudinary返回图像URL后,我想将URL发送到后端并将其保存在数据库中。问题是当我使用Cloudinary API打电话时,它并没有等待响应从Cloudinary返回,它立即在Cloudinary One之后撞到后端URL。我也使用了异步和诺言。但这是行不通的。
cloudinary.js
import axios from 'axios'
export default {
async uploadToCloudinary(data) {
let url = `url`
let config = {
headers: {
"Content-type": "multipart/form-data",
},
};
let image_url = axios.post(url, data, config).then(async res => {
let data = await res.json();
return data.secure_url
}).catch(error => {
console.log(error)
})
return image_url
}
}
main.vue
async process() {
let formy = new FormData();
formy.append("file", this.file);
formy.append("upload_preset", 'abcde');
let imageUrl = await cloudinary.uploadToCloudinary(formy)
await dataService.sendToDatabase({ image: imageUrl.secure_url}).then(res => {
console.log(res)
})
}
I am using cloudinary to upload the image and after the image URL is returned from cloudinary, I want to send the URL to the backend and save it in my database. The problem is when i call using the cloudinary api, it is not waiting for the response to come back from cloudinary, it straight away goes to hit the backend URL after the cloudinary one. I have used async-await and promise also. But it is not working.
cloudinary.js
import axios from 'axios'
export default {
async uploadToCloudinary(data) {
let url = `url`
let config = {
headers: {
"Content-type": "multipart/form-data",
},
};
let image_url = axios.post(url, data, config).then(async res => {
let data = await res.json();
return data.secure_url
}).catch(error => {
console.log(error)
})
return image_url
}
}
main.vue
async process() {
let formy = new FormData();
formy.append("file", this.file);
formy.append("upload_preset", 'abcde');
let imageUrl = await cloudinary.uploadToCloudinary(formy)
await dataService.sendToDatabase({ image: imageUrl.secure_url}).then(res => {
console.log(res)
})
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的诺言没有正确束缚。混合
异步/等待
和<代码>然后一起不是一个好主意。另外,未设置您的图像URL参数。结果,图像URL未传递给后端。Your promises are not properly chained. Mixing
async/await
andthen
together is not a good idea. Also, your image url parameter is not set. As a result, the image url is not passed to the backend.好吧,您使用
res.json()
。这通常与fetch
一起使用。您不需要在Axios上这样做。您也不需要ync /等待< / code>在您的第一个功能
Well you use
res.json()
. This is usually used withfetch
. You dont need to do that on axios. You also dont needasync / await
at ur first function