按数组顺序获取数据

时间:2019-10-20 03:14:35

标签: javascript arrays reactjs promise fetch

我有一个包含ID列表的数组。借助它,我试图从WordPress REST API中获取一些帖子数据。我设法检索了要查找的数据,但是遇到的问题是map函数生成的数组内部的对象与原始数组中的ID的顺序不同。 / p>

fetchData = async () => {
    const array = [];
    await Promise.all( ids.map( async id => {
        await apiFetch( {
            path: `/wp/v2/posts/${ id }`,
        } ).then( response => array.push( response ) );
    } ) );
    console.log( array );
};

如何确保以与原始数组相同的顺序检索和存储获取的数据?

1 个答案:

答案 0 :(得分:0)

您正在进行异步调用,因此不会按顺序获取响应。

您可以使用Map(以id作为键,以response作为值)来代替数组。

fetchData = async () => {
    const map = new Map();
    await Promise.all( ids.map( async id => {
        await apiFetch( {
            path: `/wp/v2/posts/${ id }`,
        } ).then( response => map.set(id, response) );
    } ) );

    // Display responses in 'ids' array order.
    ids.forEach(id => {
      console.log(map.get(id));
    });
};