gpt4 book ai didi

javascript - axios + Promise 给 then 方法添加参数

转载 作者:行者123 更新时间:2023-12-01 02:11:02 25 4
gpt4 key购买 nike

我在 Promise 中进行了 axios post 调用,并且我想在 Promise then 方法中获取 ajax 响应

 return new Promise((resolve, reject) => {
axios.post('/api/products/modify', product).
then(r => {
if(r && r.data && r.data.result) {
return {productId: r.data.result};
} else {
console.error("actions addproduct error occours during modifying the product! Error: " + r.data.error);
reject(r.data.error);
}
}).
catch((error) => {
console.error("actions addproduct; error occours during adding the product! Error: " + error);
reject(error);
});
}
});

当我调用 p.then(); 时,我想获取 {productId: r.data.result} 对象。

我试过这个:

p.then(r => {
console.debug("response: " + r);
});

但是不起作用。然而,ajax 调用正在到达服务器,因此 Promise 有效,但我无法将结果添加到 then 方法中。

感谢您的提前回复!

最佳答案

避免 Promise constructor antipattern !您的 return 很好,但您应该简单地抛出您的错误,然后使用 then() 已经为您创建的 promise :

return axios.post('/api/products/modify', product).then(r => {
if (r && r.data && r.data.result) {
return {productId: r.data.result};
} else {
console.error("actions addproduct error occours during modifying the product! Error: " + r.data.error);
throw r.data.error;
}
}, error => {
console.error("actions addproduct; error occours during adding the product! Error: " + error);
throw error;
});

或者没有日志:

return axios.post('/api/products/modify', product).then(r => {
if (r.data.result) {
return {productId: r.data.result};
} else {
throw r.data.error;
}
});

关于javascript - axios + Promise 给 then 方法添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49778232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com