gpt4 book ai didi

javascript - 使用 JavaScript Fetch 返回待处理的 Promise

转载 作者:行者123 更新时间:2023-12-01 00:34:41 26 4
gpt4 key购买 nike

我正在从 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

最佳答案

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.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("\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)
);

关于javascript - 使用 JavaScript Fetch 返回待处理的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58228574/

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