如何在 JavaScript 中同步等待获取成功?

问题描述 投票:0回答:2

我正在尝试执行同步循环,直到成功获取 URL。 这是我尝试过的:

let res = null 

fetch("https://jsonplaceholder.typicode.com/users/1").then((response)=>{
  return response.json();
}).then((data)=>{
  res = data;
  return data
})

while(!res){
  console.log(`${Date.now()} fetching`);
}

但是不行,因为回调没有执行,导致res = null。 我如何修改它以执行同步循环,直到成功获取 URL?

javascript node.js asynchronous
2个回答
-1
投票

嘿,看起来在代码示例中您滥用了 Promise 的力量。

我有 2 个选项可以帮助你的代码正常工作。

  1. 利用异步/等待语法的强大功能:
async function letsRock() {
   try {
      const res = await fetch("https://jsonplaceholder.typicode.com/users/1")
      // The rest of your code ...
    
      return res // Return the response (Optional)

   } catch(e) {
     // Code in case that the request fails
   }
}

注意:尽可能使用

const

文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

  1. .then
    语句中编写代码:
fetch("https://jsonplaceholder.typicode.com/users/1").then((response)=>{
  return response.json();
}).then((data)=>{
  // Use your data here this block defines than the function already was executed successfully 
})

希望它对你有用!

致以诚挚的问候!


-1
投票

我修改了你的代码。尝试一次。

let res = null;
async function fetchData() {
    while(!res) {
        await fetch(url)
              .then((response)=>{
                   return response.json();
               }).then((data)=>{
                   res = data;
               })
    }
}

fetchData();
© www.soinside.com 2019 - 2024. All rights reserved.