0

I have problems in returning the result of a promise to a variable. The only way that works for me is making a console.log, but it's not what I want.

const getAnimeVideo = async (id: string, chapter: number) => {
  const BASE_URL = `${url}${id}/${chapter}/`;
  const browser = await puppeteer.launch() ;
  const page = await browser.newPage();
  await page.goto(BASE_URL);
  const elementHandle = await page.$('.player_conte');
  const frame = await elementHandle.contentFrame();
  const video = await frame.$eval('#jkvideo_html5_api', el =>
    Array.from(el.getElementsByTagName('source')).map(e => e.getAttribute("src")));
  return video;
}

getAnimeVideo('tokyo-magnitude-80' , 1)
  .then(res => console.log(res)); // It shows me the data correctly.

const T = getAnimeVideo('tokyo-magnitude-80' , 1)
  .then(res => {
    return res; //Promise { <pending> }
  })
Chris Michael
  • 1,557
  • 3
  • 15
  • 23
  • @T.J. Crowder, I do not think the question is duplicated, which you refer to is related to ajax. In my case it's how I can return data from a promise to a variable. – Chris Michael Jun 19 '19 at 18:12
  • 1
    It's the same basic issue; your API is asynchronous. You call your `async` function without using `await`, and you assign to `T` the returned value from the call to `.then()`. Inside that `.then()` callback, you *can* get to the value, as you noted in the code right before that. Only via Promise resolution (i.e., a `.then()` callback or by using `await` in another `async` function) can you "wait" for the resolved value. – Pointy Jun 19 '19 at 18:26
  • @Pointy thanks for the comment. Could you tell me how the code should look? Apologies .. I'm a novice in Promises topics – Chris Michael Jun 19 '19 at 19:01
  • 1
    Well the thing is without using `await`, you *can't* make the code work the way you want. You either have to use `await` or else do the work inside the `.then()` callback. The linked questions have a *ton* of valuable reference material. – Pointy Jun 19 '19 at 19:16

0 Answers0