簡體   English   中英

返回已解決的承諾值

[英]Return resolved promise value

  const displayCharacters =  async () => { 
    if(filteredCharacters !== 'default'){
      const a = filteredCharacters.map(e => e.name);
      const options = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 'data' : a })
      };

      const b = await fetch("/image",options).then(res => res.json())
      return b; 

    }else{
      return "yikes";
    }
  }


  console.log(displayCharacters());

我有這個獲取請求,但是當我記錄結果時,我看到的是:

Promise {<resolved>: "yikes"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "yikes"

我只想要 promiseValue 而不是整個事情。 我該怎么做呢?

async函數立即返回一個承諾,而無需等待承諾解決。 您可以改為在函數內部使用 console.log:

  const displayCharacters =  async () => { 
    if(filteredCharacters !== 'default'){
      const a = filteredCharacters.map(e => e.name);
      const options = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ 'data' : a })
      };
      try {
        const b = await fetch("/image",options).then(res => res.json());
        console.log(b);

        //the better practice is however, to do like:
        const b = await fetch("/image",options)
        const result = await b.json(); 
        console.log(result );
      }
      catch(err) {
         console.log(err);
      }

    }else{
      console.log("yikes");
    }
  }


displayCharacters();

我知道使用 fetch 的最好方法是這樣的:

const displayCharacters =  async () => { 
  if(filteredCharacters !== 'default'){
    const a = filteredCharacters.map(e => e.name);
    const options = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ 'data' : a })
    };

    const b = await fetch("/image",options)
      .then(res => {
        // Handle API Errors
        if (!res.ok) {
          throw Error(res.statusText);
        }
        // Return if no errors
        return res.json();
      })
      // this is the data you want
      .then(data => data)
      // it will only reject on network failure or if anything prevented the request from completing
      .catch(error => {
        console.log(error.message)
      });

    return b; 

  }else{
    return "yikes";
  }
}

基本上,您將兩個 then 和一個 catch 鏈接起來以完全理解響應 - 第一個然后檢查 api 級別的錯誤 - 第二個然后獲取數據 - 當它無法像連接問題一樣到達 api 本身時調用 catch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM