我的一个服务器调用花费了将近30秒钟来返回数据,因此它总是变得不确定,因此我正在使用async并承诺解决此问题,但是却变得“不确定”。以下是我的代码段预先感谢
function fetchFunc() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then((json) => {
// console.log(json)
return json;
})
}
function resolveAfter2Seconds() {
return new Promise(resolve => {
resolve(fetchFunc());
});
}
async function asyncFunc() {
debugger
console.log("res" + resolveAfter2Seconds())
let response = await resolveAfter2Seconds();
console.log("response = " + response);
}
asyncFunc();
答案 0 :(得分:1)
正如偷窥者在前面的注释中所说,当您期望某个函数可以为您提供一个值时,您应该使用return
关键字。因此,在这种情况下,您实际上返回了fetch
响应,但忘记了返回fetch
承诺值本身。
所以您的代码应如下所示:
function fetchFunc() {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then((json) => {
// console.log(json)
return json;
})
}
function resolveAfter2Seconds() {
return new Promise(resolve => {
resolve(fetchFunc());
});
}
async function asyncFunc() {
debugger
console.log("res" + resolveAfter2Seconds())
let response = await resolveAfter2Seconds();
console.log("response = " + response);
}
asyncFunc();