使用 JavaScript Fetch 返回 Pending Promise
我正在从 Dictionary API 中获取文本,但我无法弄清楚为什么我的代码会返回待处理的承诺.但是,记录该值会返回预期的文本.这是我的代码,
I'm fetching text from a Dictionary API and I can't quite figure out why my code returns a pending promise. However logging the value returns the intended text. Here is my code,
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("
")[1]
}
test = getWord(5)
console.log(test) // Results in Pending Promise
推荐答案
由于 async
函数返回一个 Promise,您需要等待该 Promise 解决后才能使用该值
Since async
functions return a Promise, you need to wait for that promise to resolve before you can use the value
一种解决方案是将代码包装在异步 IIFE 中
One solution is to wrap your code in an async 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("
")[1]
}
let test = await getWord(5)
console.log(test) // Results in correct output
})();
但请注意:test
仍然不会是此 IIFE 之外可用的值
But note: test
is still not going to be a value available outside this IIFE
另一种解决方案是使用 Promise.then
Another solution is to use Promise.then
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("
")[1]
}
getWord(5).then(test =>
console.log(test)
);
但是,test
的值仍然只能在最终的
But, again, value of test
is still only available inside the final .then
callback
没有办法让结果同步"可用,因为异步代码在未来某个未知时间返回值 - 所以你只需要使用异步而不是尝试缩短它
There's just no way to have the result available "synchronously" since asynchronous code returns the value at some unknown time in the future - so you just have to work with asynchrony rather than try to short cut it
对我来说,您似乎正在尝试使用中间异步函数来短路异步-您不能这样做-上面的代码过于复杂
To me, it appears you are trying to use the intermediate async function to short circuit asynchrony - which you can't - the above code is over complicated way of doing
const getWord = async (difficulty) => {
const fetchParameters = api + "?difficulty=" + difficulty;
const response = await fetch(fetchParameters);
const text = await response.text();
return text.split("
")[1];
};
getWord(5).then(test =>
console.log(test)
);
相关文章