如何在映射函数中使用异步和等待顺序执行

时间:2019-11-27 10:53:36

标签: javascript asynchronous 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++])
  })

任何建议都会很有帮助

2 个答案:

答案 0 :(得分:2)

您必须等待map函数的承诺才能获得结果。

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()将其解析为有序数组,因为返回了promise数组地图功能的顺序正确。

答案 1 :(得分:-1)

尝试Promise.mapSeries进行异步等待的顺序访问。

 async function main() {

 const items = []; // Fill your items
  const articles = []; // Fill your articles

  await Promise.mapseries( items, async (item, i) => {
    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);


  //articles[i] = articles[i]+likes+comments
  articles[i].likecount = likes.likeCount
  articles[i].commentcount = comments.length
  articles[i].FileRef = item.FieldValuesAsText.FileRef
  console.log(articles[i])

  newst.push(articles[i++])
  console.log(newst)
  j++
  })