【问题标题】:Return Promise and await are the exact same? [duplicate]Return Promise 和 await 完全一样吗? [复制]
【发布时间】:2019-11-13 16:15:20
【问题描述】:

考虑以下2个函数:一个返回promise对象,一个使用await。它们在幕后的行为是否完全相同?

async function f1 (event) {
  const promise = new Promise(function(resolve, reject) {
    fetch('https://google.com')
      .then(p=>p.status)
    });
  return promise
}

async function f2 (event) {
  const res = await fetch('https://google.com');
  return res.status;
}

我相信我也可以这样称呼:

var r1 = await f1(url);
var r2 = await f2(url);

这里的问题: 1.这2个电话正确吗? 2. f1 和 f2 在钩子下,它们的行为和用法完全相同吗?

【问题讨论】:

  • 我相信会是reject(e)
  • @Intervalia behaviour 是一个有效的词。
  • 对于函数 f1,你真的不需要异步,因为你已经返回了一个 Promise。
  • 是的,它们的输出和功能是一样的

标签: javascript node.js


【解决方案1】:

如果http.get 返回一个promise,您可以简化promise 示例,使其看起来像await 示例。为了简单地回答你的问题,他们用不同的语法做同样的事情。

async function f1 (event) {
  return https
    .get(url)
    .then(res => res.statusCode);
}

async function f2 (event) {
  const res = await https.get(url);
  return res.statusCode;
}

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 1970-01-01
    • 2021-08-25
    • 2021-08-30
    • 2020-11-04
    • 2023-03-15
    相关资源
    最近更新 更多