繁体   English   中英

在 React js 中等待一个承诺

[英]Await a promise in react js

我想在实现另一个逻辑之前等待一个承诺。 例如,我有一个请求(第一个)和第二个请求(第二个)。 当我将提出第二个请求时,我想在其中等待第一个请求,然后添加额外的逻辑。 为此,我创建了:

 async function resolveAfter2Seconds() {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then( json => {
        console.log('first'); 
      })
  }
  
  async function f1() {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(async json => {
        await resolveAfter2Seconds();
        console.log('second'); 
      })
  }
  
   const click = () => {
    f1();
  }
  
  return (
    <div className="App">
      <button onClick={click}>click</button>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );

所以,当我点击按钮时,我想在控制台中first看到文本,然后再看到second 这就是我实现这个的原因:

await resolveAfter2Seconds();
console.log('second');

问题是代码按以下顺序运行: secondfirst 如何使第一个请求首先发生?

那是因为您的第一个函数会立即解析。 你所拥有的是

 async function resolveAfter2Seconds() {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json()) // happens later, when the call is completed
      .then( json => {
        console.log('first'); 
      })
    return; // happens now
  }

只需添加一个 return 语句,事情就会以正确的顺序发生

async function resolveAfter2Seconds() {
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then( // etc.
}

(顺便说一句,如果您已经在使用async函数,最好去掉then并将它们转换为await语法)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM