我正在尝试用特定的属性值填充对象数组,并在 Node.JS 环境中将 Promises 与 async/await 和 Javascript 一起使用。这是主要部分:
getPublicNotes(connectHeaders, baseurl, pubKey, noteKeyList).then((nkl) => {
if (nkl.length > 0) {
getSecurityAbEntry(connectHeaders, baseurl, nkl);
for (let count = 0; count < nkl.length; count++) {
let secGroupKey = getSecurityAbEntry(connectHeaders, baseurl, nkl[count]);
nkl[count].writeAccessKey = secGroupKey;
}
} else {
console.log("EMPTY: There are no Public Notes; nothing to process.");
}
/* for (let count2 = 0; count2 < nkl.length; count2++) {
let notesSecGroup = setNoteSecurity(connectHeaders, baseurl, nkl[count2]);
console.log(notesSecGroup);
} */
});
noteKeyList
是一个对象数组,最初为空。
getPublicNotes(...noteKeyList)
是一个异步函数,它返回 Promise 中的对象数组。
getSecurityAbEntry(...nkl[count])
是一个异步函数,它接受单个对象并在 Promise 中返回单个 writeAccessKey
值。在 for 循环结束时,noteKeyList
数组如下所示:
[
{
abEntryKey: 'abc124der',
noteKey: '098ert'
writeAccessKey: Promise { <pending> }
},
{
abEntryKey: 'def321red',
noteKey: '392tkf'
writeAccessKey: Promise { <pending> }
},
{
abEntryKey: 'ghi645green',
noteKey: '9384fds'
writeAccessKey: Promise { <pending> }
},
...
]
如何使用 then() 访问每个对象的 writeAccessKey 属性?
setNoteSecurity()
是我接下来想要在数组中的每个对象上使用的,但不知道如何挖掘数组中的每个对象以输入到这个异步函数中。
建议?
PS:我可以为您提供每个异步函数的内容,但我想我将从这个开始,以防函数的内容不是必需的。
您需要将
nkl
数组映射到一个新数组,其中每个 getSecurityAbEntry()
调用都已得到解决,然后将其传递给 Promise.all()
以等待它们全部解决。
const nkl = await getPublicNotes(connectHeaders, baseurl, pubKey, noteKeyList);
const finalList = await Promise.all(
nkl.map(async (nk) => ({
...nk,
writeAccessKey: await getSecurityAbEntry(connectHeaders, baseurl, nk),
})),
);
console.log(finalList);
如果你不想使用
async
/ await
,那么等效的看起来像这样
getPublicNotes(connectHeaders, baseurl, pubKey, noteKeyList)
.then((nkl) =>
Promise.all(
nkl.map((nk) =>
getSecurityAbEntry(connectHeaders, baseurl, nk).then(
(writeAccessKey) => ({
...nk,
writeAccessKey,
}),
),
),
),
)
.then((finalList) => {
console.log(finalList);
});