-2

I want to return the data to a variable. I have resolved the promise and making it print to console. I want that the data should be access outside and can be used by a variable. I want whatever values are there in console.log(x) , should come outside the loop in a variable ( say variable name z)

 var libobj =await service.getdata(); //----------> returning from service file and libobj is returning  promise (fullfilled)

// var z; -----Data needed here or below the map loop

libobj.map( (res: any) => 
(res.then((x : any )=>console.log(x)) )); //--------> console .log(x) printing all  the data needed

1 Answers1

-1

Following is an example to showcase Promise.all...

let createAPromise = (x) => new Promise((res, rej) => setTimeout(() => { console.log(`Resolving ${x}`); res(x)}, x));


async function test() {

  const libobj = [300, 500, 700].map(x => createAPromise(x));

  const values = await Promise.all(libobj);

  console.log('Resolved all with', values);
}

test();

This example is only to highlight a way of Promise.all to obtain a final value from a collection of promises...

Nalin Ranjan
  • 1,728
  • 2
  • 9
  • 10
  • 1
    I replied to your comment (I didn't notice your answer). The point I was trying to make there was that assigning an external value from a `.then` callback doesn't work, but I see that your answer didn't have this problem. :) `let` or `const` makes little difference here. – FZs Jan 21 '22 at 10:05