-1

I have 1 function in Nodejs that return a list of recipient:

var recipientList = [];
userService.listUser().then( result => {
    var listPSID = result.filter(result => !'279'.includes(result));
    recipientList = listPSID.slice();
    console.log(recipientList);
});

Now I want to access that list OUTSIDE the function, something likes:

console.log(recipientList[0]);

How can I do that? Thank you all.

1 Answers1

0

If you're using Promises, you cannot access it outside the function. If you use async / await instead, it should work.

async function getList(){
    let result = await userService.listUser();
    var listPSID = result.filter(result => !'279'.includes(result));
    recipientList = listPSID.slice();
    console.log(recipientList[0]);
}
Gaurav Punjabi
  • 153
  • 1
  • 6
  • Thank you very much for your answer, but what I expected is like: async function getList(){ recipientList = listPSID.slice(); }; const abc = recipientList[1]; Is there any way to do that? – tuanha1709 Jun 12 '19 at 02:57
  • @tuanha1709 You can initialize the variable outside the function possibly, but I still don't think it will be possible since it is async. – Gaurav Punjabi Jun 12 '19 at 05:17