代码之家  ›  专栏  ›  技术社区  ›  Kevin.a

返回已解决的承诺值

  •  0
  • Kevin.a  · 技术社区  · 6 年前
      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"
    

    我只想要约定的价值,而不是它周围的一切。我该怎么做?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Addis    6 年前

    这个 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();
    
        2
  •  0
  •   thinparfiet    6 年前

    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";
      }
    }
    

    基本上你用链子把两个鱼饵和一个鱼饵连在一起就能完全理解对方的反应 -然后给你数据 -catch在无法像连接问题一样访问api本身时调用

    推荐文章