0

I am trying console log the variable arrItems outside of .then(). any suggestion? Thanks in advance.

protected fun(){
    sp.web.lists.getByTitle("Requests")
    .items.get()
    .then((items: any[]) => {

    var arrItems = items.map((order) => {
    var info = {
      "Id": order.Id, "File": order.FileName
    }
    return info;
  })
  console.log(arrItems) // works
 },
);

 console.log(arrItems) // doesent works
}
Aris Vang
  • 23
  • 9

2 Answers2

0

You could omit the .then(), by using the asyn/await approach, like so:

async fun(){
    let items: any[] = await sp.web.lists.getByTitle("Requests").items.get();

    var arrItems = items.map((order) => {
        var info = {
            "Id": order.Id, "File": order.FileName
        }
        return info;
    });

    console.log(arrItems);
}
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
0

The .get is a promise, which is resolved async. That means that other code will be executed before the promise resolved.

If you're not sure how this works, I'd recommend reading some posts / documentation like this.

You could use the await es6 tag to wait until the promise is resolved, and then console log the result.

Example from MDN

function resolveAfter2Seconds(x) { 
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(x);
        }, 2000);
      });
    }
    
    async function f1() {
      var x = await resolveAfter2Seconds(10);
      console.log(x); // 10
    }
    
    f1();
Olaf
  • 1,038
  • 8
  • 20