按照数组的顺序获取数据

问题描述 投票:1回答:1

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

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

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

javascript arrays reactjs promise fetch
1个回答
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));
    });
};
© www.soinside.com 2019 - 2024. All rights reserved.