javascript - 无法从 Promise 中检索数据

标签 javascript node.js promise

我无法使用 then() 从 Promise 中检索数据。我哪里出错了?

async function A(){
    await new Promise((resolve, reject) => setTimeout(()=>{},1000));
    return 45;
}
A().then(data => console.log(data))

我正在使用 Node.js 运行此代码。 我期望输出打印 45。但是程序只执行了 1 秒并且不打印任何内容。 如果我删除超时语句,我可以打印 45。 我哪里出错了?

最佳答案

您需要解决您的 Promise,然后 return 才能运行。

async function A() {
  await new Promise((resolve, reject) => setTimeout(() => resolve(), 1000));
  return 45;
}
A().then(data => console.log(data))

您还可以从A函数返回promise,然后使用async/await

function A() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(45), 1000)
  })
}

(async() => {
  const res = await A();
  console.log(res)
})()

关于javascript - 无法从 Promise 中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884733/

相关文章:

javascript - 为什么 Node fs.watchFile 使测试无法完成?

javascript - 我可以提前结束 Promise.each 吗?

javascript - 通过 jQuery ajax 发送大型 JSON 时出现 404、TypeMismatchError 或 "Not enough storage is available to complete this operation"错误

javascript - 在 Chrome 扩展中使用远程 JavaScript

node.js - 使用 Node Canvas 从右到左编写段落,基于开罗的实现

javascript - 使用 Nodejs 请求模块对返回未定义进行地理编码的函数

javascript - ES6 类 Promise 链——访问 'this'

javascript - 我如何让 Promise.all 按预期执行我的 promise ?

javascript - 如何在 jquery mobile 中调用页面加载函数以及如何将数据从一个页面传递到另一个页面

javascript - 禁用/启用点击播放功能