简体   繁体   中英

Async Promiss.all not waiting for callback

I am having an array of posts and looping through each post like this:

arr = [] 
obj = {}
await Promise.all(allPosts.map(async (post) => { 
  let userData = await User.getByUserId(post.user_id);
            obj.userData = userData[0];
            obj.postDetails = post;
let productData = await Post.getPostTaggedProducts(post.id);
            obj.productData = productData;
            arr.push(obj)
            }))

This is the code in model:

User.getByUserId = (id) => {
  return new Promise(function (resolve, reject) {
    config.query("SELECT * FROM Users WHERE id = ?", id, (err, result) => {
      if (err) {
        reject(err)
      } else {
        resolve(result)
      }
    })
  })
}

But the arr is not pushing the obj with new data from callbacks. How can I make sure the loop goes further only when the data is received from callback. Can anyone tell me what I am doing wrong?

Promise.all takes an array of promises and returns array of each promise resolved value

So,

let arr = await Promise.all(allPosts.map(post => getPosts(post)));

async function getPosts(post){
    let obj = {};
    let userData = await User.getByUserId(post.user_id);
    obj.userData = userData[0];
    obj.postDetails = post;
    let productData = await Post.getPostTaggedProducts(post.id);
    obj.productData = productData;
    return obj;
};

Explanation: getPosts function takes post as a parameter and do your per post queries and returns Promise (which will get resolved to obj). then we map allPosts to getPosts for each post, so by this Promise.all will get array of promises.

You can also do this like: let arr = [];

for(let post of allPosts){
    let obj = {};
    let userData = await User.getByUserId(post.user_id);
    obj.userData = userData[0];
    obj.postDetails = post;
    let productData = await Post.getPostTaggedProducts(post.id);
    obj.productData = productData;
    arr.push(obj);
};

Note: for loop should be inside an async function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM