我想知道下面的代码是如何工作的(它在下拉列表中显示正确的选项),即使intellij中的警告说“承诺返回的承诺被忽略”,并建议对代码进行更改。代码的初始版本:
import React, { useState, useEffect } from "react";
import axios from "axios";
const Cake = () => {
const [ing, setIng] = useState([]);
const [error, setError] = useState("");
const getIngredients = async () => {
// returns an array of strings
const url = new URL("someUrl");
const result = await axios.get(url.toString());
return result.data;
};
useEffect(() => {
new Promise((resolve, reject) => {
getIngredients()
.then((response) => setIng(response))
.then((response) => resolve(response))
.catch((error) => setError(error));
});
}, []);
return (
<div>
<Select options={ing} />
</div>
);
};
export default Cake;
intellij建议在我的承诺中加上“then”,如下所示:
useEffect(() => {
new Promise((resolve, reject) => {
getIngredients()
.then((response) => setIng(response))
.then((response) => resolve(response))
.catch((error) => setError(error));
}).then((r) => console.log(r));
}, []);
1条答案
按热度按时间k4ymrczo1#
你不应该创建一个
new Promise
在这里(正如intellij所说,它甚至没有在任何地方使用),它也是Promise
构造函数反模式到resolve
政府的承诺.then()
收回另一个承诺。你所需要的效果就是