简体   繁体   English

为什么异步/等待变量返回未定义?

[英]Why async/await variable return undefined?

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? 我认为这将是一个欢乐的对象?

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. await x求值为x的值,或者,如果该值是一个承诺,则求值为承诺所解析的值。

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). 如果$undefined ,则request()要么返回undefined要么返回解析为undefined的promise(不太可能)。 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. 仅当cherrio对象iff request实际上返回cherrio对象或解析为cherrio对象的Promise时才是。

How do I convert an existing callback API to promises? 如何将现有的回调API转换为Promise? might help you to solve your actual coding problem. 可能会帮助您解决实际的编码问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM