gpt4 book ai didi

javascript - 如何在 map 函数中使用 async 和 await 进行顺序执行

转载 作者:行者123 更新时间:2023-11-30 19:05:05 24 4
gpt4 key购买 nike

嗨,对我来说 async 和 await 是安静的新事物。我有需要 await 方法的函数调用,因此我需要使用 async 和 await。我正在获取值,但它们没有按顺序排列。

下面是我的异步和等待映射函数

items.map(async (item) =>{
const itemx = await
Promise.all([w.getFileByServerRelativeUrl(item.FieldValuesAsText.FileRef).getItem()]);
var likes = await Promise.all(itemx.getLikedByInformation());
const comments = await Promise.all(itemx.comments.get());
articles[i].likecount = likes.likeCount
articles[i].commentcount = comments.length
articles[i].FileRef = item.FieldValuesAsText.FileRef
newst.push(articles[i++])
})

任何建议都会很有帮助

最佳答案

您必须等待 map 函数的 promise 才能按顺序获得结果。

async function main() {
const items = []; // Fill your items
const articles = []; // Fill your articles

// Async map function return promise for each item
const promises = items.map(async (item, i) => {
console.log(item.FieldValuesAsText.FileRef);
const itemx = await Promise.all([
w.getFileByServerRelativeUrl(item.FieldValuesAsText.FileRef).getItem()
]);

console.log(item);
var likes;
likes = await Promise.all(itemx.getLikedByInformation());
console.log("like " + likes.likeCount);
const comments = await Promise.all(itemx.comments.get());
console.log("Comments Count " + comments.length);

// Create new object by appending articles[i],likes,comments
return {
...articles[i],
likecount: likes.likeCount,
commentcount: comments.length,
FileRef: item.FieldValuesAsText.FileRef
};
});

// Here you have everything in order.
const newst = await Promise.all(promises);
}

每个映射项函数异步运行,因此无法保证映射函数内部的顺序,但您可以从映射函数返回值,使用 await Promise.all()< 可以将其解析为有序数组 因为 map 函数返回的 promise 数组的顺序是正确的。

关于javascript - 如何在 map 函数中使用 async 和 await 进行顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59068542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com