javascript async等待反应。 setState不等待等待

时间:2019-06-06 08:59:27

标签: reactjs async-await ecmascript-7

我正在构建一个组件,以获取组的成员,然后从api下载图像。它在componentDidMount中使用async等待,并且照片可以正确返回。但是,即使我使用异步等待。它不等待图像解析。因此,在setState中它将返回一个promise。

我的组件:

import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faUser } from "@fortawesome/free-solid-svg-icons";
import {
    GetGroupMembers,
    getImage
} from "../../../HttpRepositories/oneApiRepository";

class TeamCardPersonaMembers extends React.Component {
    constructor(props) {
        super(props);
        this._isMounted = false;
    }

state = {
    members: []
};

async componentDidMount() {
    this._isMounted = true;
    let members = await GetGroupMembers(this.props.teamId);

    const membersToSend = await members.map(async member => {
        const memberPhotoUrl = `${process.env.REACT_APP_ONE_API_URL}/api/users/${
            member.id
        }/photo`;

        let memberPhoto = await getImage(memberPhotoUrl);
        member.photo = memberPhoto;
        return member;
    });

    if (this.state.member !== "error" && this._isMounted) {
        this.setState({ members: membersToSend });
    }
}

render() {
    let members = [];

    console.log(this.state);

    if (this.state.members.length > 0) {
        this.state.members.map(member => {
            console.log("this is the member ", member);
            const memberImg = (
                <img
                    key={member.id}
                    src={member.photo}
                    alt={member.displayName}
                    className="team-card-persona-wrapper"
                    title={member.displayName}
                />
            );

            members.push(memberImg);
        });
    }

    return <React.Fragment>{members}</React.Fragment>;
}

componentWillUnmount() {
    this._isMounted = false;
}

}

console.log

enter image description here

导出默认的TeamCardPersonaMembers;

任何帮助或指针将不胜感激!干杯!

2 个答案:

答案 0 :(得分:1)

map的标准实现不等待传递给它的回调。导致map调用在回调完成之前返回promise。您有两种选择。

    const membersToSend = []
    for (const member of members) {
        const memberPhotoUrl = `${process.env.REACT_APP_ONE_API_URL}/api/users/${
            member.id
        }/photo`;

        let memberPhoto = await getImage(memberPhotoUrl);
        member.photo = memberPhoto;
        membersToSend.push(member);
    }

或推出自己的异步映射实现。

Array.prototype.mapAsync = async function (callback) {
  const output = []
  for (const el of this)
    output.push( await callback(el) ) <-- // Note the await on the callback

  return output
}

编辑: 注意,上述方法按顺序执行promise。正如杰德(Jed)所指出的,如果您想一次触发所有请求并等待它们解决,

const memberPhotos = await Promise.all(members.map(member => {
   const memberPhotoUrl = `${process.env.REACT_APP_ONE_API_URL}/api/users/${
            member.id
        }/photo`;

        return getImage(memberPhotoUrl);
}))

但是如果请求太多,此方法可能会使您的网络超载,请谨慎使用。

答案 1 :(得分:0)

await关键字仅适用于其他异步函数或返回Promise的函数。因此,我认为像您一样在await上使用members.map是没有道理的。那只是正常的同步功能调用。您需要将其设置为:

https://flaviocopes.com/javascript-async-await-array-map/