为什么异步/等待变量返回未定义? [英] Why async/await variable return undefined?

查看:60
本文介绍了为什么异步/等待变量返回未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码...

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 的计算结果为 x 的值,或者,如果该值是一个承诺,则计算为该承诺解析为的值.

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

示例:

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

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

如果 $ undefined ,则 request()要么返回 undefined ,要么返回为 undefined (不太可能).查看其文档或源代码,以了解到底发生了什么.

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?

只有cherrio对象 iff request 实际上会返回cherrio对象或解析为cherrio对象的Promise.

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

如何将现有的回调API转换为Promise?可以帮助您解决实际的编码问题.

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

这篇关于为什么异步/等待变量返回未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆