等待的承诺仍然返回<pending>

用户名

我有一个关于人的数据对象数组。每个人员对象都包含0-n个用于其他信息(人员的访客)的URL。

我想处理此列表,调用每个“来宾” URL,并在原始数据集中包括来宾的名字。

上下文:这是一个AWS lambda函数。我正在使用lambda-local本地运行。lambda-local -l index.js -e fixtures/test_event1.json)。

我成功使用了await / async来检索初始数据集。

但是我无法获得有关来宾信息的更多电话咨询服务。即使结果等待,它始终显示一个未决的Promise。

// index.js

const fetch = require('node-fetch');

exports.handler = async function(event){

    try {
        let registrations = await getEventRegistrations();
        console.log(registrations);

/* All good here - sample console output
[ { contactId: 43452967,
    displayName: 'aaa, bbb',
    numGuests: 0,
    guestUrls: [] },
  { contactId: 43766365,
    displayName: 'bbb, ccc',
    numGuests: 1,
    guestUrls:
     [ 'https://<URL>' ] },
  { contactId: 43766359,
    displayName: 'ccc, ddd',
    numGuests: 2,
    guestUrls:
     [ 'https://<URL>',
       'https://<URL> ] } ]
*/

        // Expanding the guest URLs is proving problematic - see expandGuests function below
        registrations = registrations.map(expandGuests);
        console.log(registrations);


/* Registrations are just pending Promises here, not the real data

[ Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> } ]

*/

        return {
            statusCode: 200,
            headers: {
                'Access-Control-Allow-Origin': '*',
            },
            body: JSON.stringify(registrations),
        };
    }
    catch (exception) {
        console.log(exception);
        return {
            statusCode: 500,
            body: 'Unable to retrieve data.'
        };
    }
};

function getEventRegistrations() {
    return fetch('<URL>')
    .then(res => res.json())
    .catch(function (error) {
        console.log('Event registrants request failed', error);
        return null;
    });
}

function getGuestName(url) {
    return fetch(url)
    .then(res => res.json())
    .then(guest => guest.DisplayName)
    .catch(function (error) {
        console.log('Guest name request failed', error);
        return null;
    });
}

async function expandGuests(data) {

    const promises = data.guestUrls.map(url => getGuestName(url));
    data.guestNames = await Promise.all(promises);

    return data;
}


如何解决这些待处理的承诺,从而返回有用的数据?

谢谢。

y布

注释正确指出指出映射async函数将返回Promises数组。他们没有明确提及的是您有两张地图,而哪一张是有问题的。

问题出在行中:

reservations = reservations.map(expandGuests);

每次使用地图时,您都需要真正解决返回的承诺。

所以:

const mappedPromises = reservations.map(expandGuests);  //returns an Array of Pending promises
const mappedReservations = await Promise.all(mappedPromises);  //resolves the promises

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章