我正在从Dictionary API中获取文本,但我不太清楚为什么我的代码会返回未决的Promise。但是,记录该值将返回预期的文本。这是我的代码,
const getWord = (difficulty) => {
const fetchParameters = api + "?difficulty=" + difficulty
let outputWord = fetchWord(fetchParameters).then(value => {
console.log(value) // ->Logs intended text
return value
})
return outputWord // -> Returns Pending Promise
}
async function fetchWord(fetchParams) {
const response = await fetch(fetchParams)
const text = await response.text()
return text.split("\n")[1]
}
test = getWord(5)
console.log(test) // Results in Pending Promise
答案 0 :(得分:3)
由于async
函数返回一个Promise,因此您需要等待该Promise解析后才能使用该值
一种解决方案是将代码包装在异步IIFE中
(async () => {
const getWord = (difficulty) => {
const fetchParameters = api + "?difficulty=" + difficulty
let outputWord = fetchWord(fetchParameters).then(value => {
console.log(value) // ->Logs intended text
return value
})
return outputWord // -> Returns Pending Promise
}
async function fetchWord(fetchParams) {
const response = await fetch(fetchParams);
const text = await response.text();
return text.split("\n")[1]
}
let test = await getWord(5)
console.log(test) // Results in correct output
})();
但是请注意:test
仍然不是该IIFE之外的可用值
另一种解决方案是使用Promise。然后
const getWord = (difficulty) => {
const fetchParameters = api + "?difficulty=" + difficulty
let outputWord = fetchWord(fetchParameters).then(value => {
console.log(value) // ->Logs intended text
return value
})
return outputWord // -> Returns Pending Promise
}
async function fetchWord(fetchParams) {
const response = await fetch(fetchParams);
const text = await response.text();
return text.split("\n")[1]
}
getWord(5).then(test =>
console.log(test)
);
但是,test
的值仍然仅在最终的.then
回调中可用
由于“异步”代码会在将来某个未知的时间返回值,因此无法“同步”获得结果-因此您只需要使用异步方法,而不是尝试将其缩短即可。
在我看来,您似乎正在尝试使用中间异步功能来缩短异步-您不能-上面的代码过于复杂了
const getWord = async (difficulty) => {
const fetchParameters = api + "?difficulty=" + difficulty;
const response = await fetch(fetchParameters);
const text = await response.text();
return text.split("\n")[1];
};
getWord(5).then(test =>
console.log(test)
);
答案 1 :(得分:-1)
因为您在基本功能中使用了异步功能。在您的情况下,最好使用:
const getWord = word => { // Created function that will be executed if promise resolve.
console.log(word);
}
const getOutputWord = difficulty => {
const fetchParameters = api + "?difficulty=" + difficulty;
let outputWord = fetchWord(fetchParameters).then(value => {
getWord(value); // pass value of promis
});
}
async function fetchWord(fetchParams) {
const response = await fetch(fetchParams)
const text = await response.text()
return text.split("\n")[1]
}
getOutputWord(3) // will execute getWord and return result in console