可以使用 async/await 语法来获取 promise 的返回值并赋值,示例代码如下:

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
}

async function main() {
  const result = await fetchData();
  console.log(result);
}

main();

在这个例子中,fetchData 函数返回一个 promise,使用 await 关键字等待该 promise 完成并返回数据。在 main 函数中,使用 await 关键字调用 fetchData 函数并等待其返回结果,将结果保存在 result 变量中并打印出来。

React 获取 Promise 返回值并赋值:Async/Await 方法

原文地址: https://www.cveoy.top/t/topic/nHT4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录