【发布时间】:2019-12-08 08:39:16
【问题描述】:
我有一组关于人的数据对象。每个人员对象都包含 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;
}
如何解决这些待处理的 Promise 并返回有用的数据?
谢谢。
【问题讨论】:
-
你不能。承诺是一种传染性。如果一个函数使用它们,那么每个使用该函数的函数都必须使用它们。这就是异步代码的工作原理。
-
每个
async函数都会返回一个承诺。他们就是这样工作的。因此,您必须在您的async函数调用中使用.then()或await才能获得其最终解析值。
标签: javascript node.js asynchronous es6-promise