【问题标题】:Is it possible to make this code use await/async rather than promises?是否可以让这段代码使用等待/异步而不是承诺?
【发布时间】:2022-02-17 02:17:56
【问题描述】:

我有这个现有的功能,效果很好:

const fetchWrapper = (resource, init) => {
  console.log('About to fetch...', resource)
  const p = fetch(resource, init)

  p.then(
    (response) => {
      console.log('The response is:', response)
    },
    (error) => {
      console.log('The error is:', error)
    }  
  )
  return p
}

我尽可能使用 async/await。但是,我认为这样做实际上可能。 主要问题是我想返回fetch()返回的promise,这样调用函数就可以像往常一样await

但我也希望在调用fetch()(这是最简单的部分)之前发生额外的事情,然后在网络响应之后立即发生。

为此,我将两个回调(响应和错误)附加到fetch() 返回的承诺。

如果我使用 Promise,我将不得不 await 进行 fetch() 调用 - 但是调用者将在 Promise 得到解决之前不会收到响应,这不是我想要的。

那么...是否有可能将此代码转换为完全异步/等待?

【问题讨论】:

    标签: javascript async-await


    【解决方案1】:

    下面的代码使用 async 和 await,与您的代码做同样的事情:

    // A simple promise response
    const mockFetch = async (resource, init) => 'Response'
    
    const fetchWrapper = async (resource, init) => {
        console.log('About to fetch...', resource)
    
        // You'll replace 'mockFetch' with 'fetch'
        const p = mockFetch(resource, init);
    
        // You can use a named function instead
        (async () => {
            try {
                const response = await p
                console.log('The response is:', response)
            } catch (error) {
                console.log('The error is:', error)
            }
        })()
    
        return p
    }
    
    (async () => {
        const response = await fetchWrapper('', {})
        console.log(response)
    })()

    mockFetch 用于演示目的,您需要将const p = mockFetch(resource, init); 删除并替换为const p = fetch(resource, init);

    【讨论】:

    • 当然。我在想什么?哦,我的...
    【解决方案2】:

    可能是这样的:

    const fetchWrapper = async (resource, init) => {
      try {
        const response = await fetch(resource, init);
        console.log('The response is:', response);
        return { success: true, response };
      } catch(error) {
        console.log('The error is:', error);
        return { success: false, error };
      }
    }
    
    

    【讨论】:

      【解决方案3】:

      async function fetchPost() {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {headers: {"Content-Type": "application/json"}});
      
        const post = await response.json();
      
        console.log(post)
      
        return post;
      }
      
      fetchPost() // Returning a Promise with the post

      【讨论】:

        【解决方案4】:
        const getData = async () => {
           try{
             const fetchData = await fetch(url, {
              method: "GET",
              headers: {
                "Content-Type": "application/json",
              },
            });
           if (fetchData.ok == true) {
             const respons = await response.json();
             return respons;
           } else {
            throw new Error("error")
           }
        
         } catch (err) {
             console.log(err)
         }
        }
        
        

        【讨论】:

          【解决方案5】:

          要省略 .then() / .catch() 的用法,您可以这样做:

          const fetchWrapper = (resource, init) => {
          
              // do stuff before fetch here ^^ 
              // ...
          
              // call the fetch
              const p = fetch(resource, init)
          
              const afterFetchEffects = async () => {
          
                  // since it is "detached" (i call it like so..) 
                  // you should ofc use try/catch
                  try {
          
                      // wait for the fetch() to finish
                      await p
          
                      // do some stuff after fetch
                      // ... 
              
                  } catch(err) {
                      console.error('Error in detached after fetch promise..', err)
                  }
              }
          
              // execute the wrapper which executes something after the fetch..
              // do not await it then it will do its own business.
              afterFetchEffects()
          
              // pass fetch immediatly back
              return p
          
          }
          

          我不确定哪种方法更具可读性^^

          【讨论】:

            猜你喜欢
            • 2018-02-14
            • 2017-06-15
            • 1970-01-01
            • 2020-04-22
            • 2018-02-03
            • 2018-03-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多