Home > front end >  Why objects key still has unknow promise , though I have used await for mapping
Why objects key still has unknow promise , though I have used await for mapping

Time:10-21

I'm new to javascript. as I know using array.map over async function returns array of promises. and I can use await Promise.all to reolve all promise and it returns me data. I want to understand how can I use asyn function inside array of object's key. As I know using async function it never block as execution for unimportant line, ( here other execution is not dependent on url , so I'm trying to make it asynchronous)

async function showPost() {
  const posts = [
    { title: 'a', url: ['q', 'o'] },
    { title: 'b', url: ['t', 'y'] },
  ];
  const formattedPost = await formatPosts(posts);
  console.log(formattedPost);
}

const formatPosts = async (posts) => {
  const formattedPosts = await Promise.all(   // NOTE: await promise.all on map
    posts.map(async (post) => {
      post.url = addUrl(post.url);    //NOTE: here if I don' add await here post.url is Promise<Unknown>
      return post;
    })
  );
  return formattedPosts;
};

const addUrl = async (d) => {
  const mm = await Promise.all(d.map((item) => item   '-dummyUrl'));
  return mm;
};

showPost();

**CODE 1 without await , but inside await Promise.all ** enter image description here

CODE 2 with AWAIT on addURL call I get output

enter image description here

Why is it not resolving though it is inside await promise.all

thanks for help in advance

CodePudding user response:

When you call Promise.all(), you're resolving the promises returned by the map() function. When you don't add await to addURL(), you're replacing that value in the object with a promise object, which isn't resolved by Promise.all().

Promises are still promises, even after they resolve.

On top of this, Array.prototype.map() isn't an async function, so addURL() doesn't need to be async, which makes adding await pointless.

CodePudding user response:

I know using array.map over async function returns array of promises, and I can use await Promise.all to resolve all promise and it returns me data.

This will just wait for the promise in the array that was passed to Promise.all, not "all promises" anywhere.

Notice that without the await, you don't need to make the map callback an async function, and you don't need to wait for the promises in the mapped array then; your current code is exactly equivalent to

const formatPosts = async (posts) => {
  const formattedPosts = posts.map((post) => {
    post.url = addUrl(post.url);
    return post;
  });
  return formattedPosts;
};

Why objects key still has unknown promise

Because you assigned a promise object to the object property. Never did you instruct anything to wait for that promise. This is what would be fixed by doing

post.url = await addUrl(post.url);
  • Related