【问题标题】:async await returning a Promise and not a valueasync await 返回一个 Promise 而不是一个值
【发布时间】:2019-09-18 05:17:02
【问题描述】:

在全栈应用程序上工作我正在调用从数据库中检索信息并将其返回的后端。事情是,当我期望获得价值时,我只得到一个Promise {<pending>}。我已经在后端代码上验证了我实际上得到了来自数据库的响应并将其发送回前端,所以我不确定为什么没有解决承诺。对此有何想法/建议?

这是我试图调用后端并显示信息的组件。 console.log 是显示 Promise {<pending>}

getTheAsset = async id => {
    try {
        const response = await this.props.getAsset(id)
            .then(result => {
                console.log("[DisplayAsset] Promise result: ", result);
            });

    } catch(error) {
        console.log("[DisplayAsset] error: ", error);
    }
}

render() {
    const asset = this.getTheAsset(this.props.match.params.id);
    console.log("[DisplayAsset] asset - ", asset);
    return (
        <div className="container">

        </div>
    );
}

以下是进行 API 调用的 redux 操作。

export const getAsset = (id) => async dispatch => {
  const response = await axios.get(`http://localhost:8181/api/asset/${id}`);
  dispatch({
    type: GET_ASSET,
    payload: response.data
  });
}

我已经包含了后端的快照,表明我实际上从数据库中获取了一个值。

我也发现了这个很棒的 answer,但仍然没有太多运气将它应用到我的情况。

【问题讨论】:

    标签: javascript reactjs redux promise


    【解决方案1】:

    异步函数总是返回承诺;这就是他们所做的。 Async/await 的存在是为了简化与 Promise 相关的语法,但它不会改变涉及 Promise 的事实。

    对于 React 组件,您需要有一个状态值,该值一开始表明它尚未加载,然后您开始异步工作,并在完成时更新状态。如有必要,您可以在加载时渲染占位符。

    state = {
      asset: null,
    }
    
    componentDidMount() {
      this.getTheAsset(this.props.match.params.id)
        .then(result => this.setState({ asset: result });
    }
    
    render() {
      if (this.state.asset === null) {
        return null; // or some other placeholder.
      } else {
        return (
          <div className="container">
    
          </div>
        );
      }
    }
    

    【讨论】:

    • 所以我不完全确定的是,当我知道结果直接从后端返回时,为什么我会得到一个未决的承诺。这是 Promise 的正常行为吗?
    • @Dan - 你得到一个未决的承诺,因为承诺是异步的。语句console.log("[DisplayAsset] asset - ", asset);axios.get 完成请求之前执行,更不用说有时间得到响应了。这就是异步的工作原理。
    • 所以我应用了@Nicholas 提供的解决方案(顺便说一句!),但asset 始终为空。 @Jaromanda,我明白你所说的异步性,我理解它,但是当承诺得到解决时,有没有办法更新组件?目前它始终处于待处理状态:(
    猜你喜欢
    • 2018-06-11
    • 2017-09-11
    • 2021-12-28
    • 2019-12-02
    • 2019-01-27
    • 2019-05-28
    • 1970-01-01
    相关资源
    最近更新 更多