0

Below is my code...

async function getItemDetalil(url) {
  const $ = await request(url, (err, res, body) => {
      return cheerio.load(body);
  });
  console.log($);
}

Why my '$' is undefined? I assume it will be a cheerio object?

Dreams
  • 8,288
  • 10
  • 45
  • 71
  • 1
    *"I assume it will be a cheerio object?"* Why do you assume that? Have you read the documentation of `request` of looked at its implementation? The function probably returns `undefined`. You cannot use `await` to magically get the return value from the callback. The function you `await` should return a promise. It would only be cherrio object **iff** `request` actually returns a cherrio object or a promise that resolves to a cherrio object. – Felix Kling Oct 12 '17 at 17:11
  • Have you tried using a `var` or `let` instead of a `const`? – Get Off My Lawn Oct 12 '17 at 17:11
  • Is `(err, res, body) => { return cheerio.load(body); }` a callback function? Can you include full text of `request` at Question? – guest271314 Oct 12 '17 at 17:12
  • @GetOffMyLawn I try and still return undefined – Dreams Oct 12 '17 at 17:12
  • @guest271314 Yes of course it is, it's a function passed as a callback to another function. – Bergi Oct 12 '17 at 17:13
  • What makes you think `request` returns a promise? – Bergi Oct 12 '17 at 17:13
  • @Bergi Yes, though is that fact obvious to OP? – guest271314 Oct 12 '17 at 17:13
  • Magic, of course. – Kevin B Oct 12 '17 at 17:14
  • 2
    You are probably looking for [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/218196) – Felix Kling Oct 12 '17 at 17:15

1 Answers1

2

Why async/await variable return undefined?

await x evaluates to the value of x or, if that value is a promise, to the value the promise resolves to.

Example:

// Value
(async function() {
  console.log('Normal value', await 42);
}());

// Promise resolution
(async function() {
  console.log('From promise:', await Promise.resolve(42));
}());

If $ is undefined, then request() either returns undefined or a promise that resolves to undefined (unlikely). Have a look at its documentation or source code to find out what exactly is happening.


I assume it will be a cheerio object?

It would only be cherrio object iff request actually returns a cherrio object or a promise that resolves to a cherrio object.

How do I convert an existing callback API to promises? might help you to solve your actual coding problem.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143