【问题标题】:The promise get resolved in undefined [duplicate]承诺在未定义中得到解决[重复]
【发布时间】:2021-05-12 04:58:14
【问题描述】:

我试图了解 Promise 和 async-await 的工作原理,我构建了以下代码来获取计算机上已连接设备的列表,但它返回“未定义”。

var iosDevice = require("node-ios-device");

const the_action = () => {
  iosDevice.devices(function (err, devices) {
    if (err) {
      console.error("Error!", err);
    } else {
      return devices;
    }
  });
}

const create_promise = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(the_action()), 100);
  });
};

const the_devices = create_promise();

const resolvePromise = (promise) => {
  promise
    .then((result) => console.log(result))
    .catch((error) => HTMLFormControlsCollection.log(error));
};

resolvePromise(the_devices);

我正在使用节点从终端运行上述脚本:

$> 节点 the_script.js

我做错了什么或错过了什么?

提前谢谢你

【问题讨论】:

    标签: javascript node.js async-await promise


    【解决方案1】:

    the_action 没有返回任何内容。您的 return 语句只是从 iosDevice.devices 回调返回 - 但包含函数不返回任何内容。这就是你的问题所在。如果你让the_action 返回一些东西,它会在你的承诺解决方案中冒泡并最终得到 console.logged

    【讨论】:

    • 感谢您的回答,根据您的建议更新代码:let conn_dev; const the_action = () => { iosDevice.devices(function (err, devices) { if (err) { console.error("Error!", err); } else { conn_dev = devices; } }); return conn_dev } 导致相同的“未定义”结果
    • @viking_biking 这一定意味着您的 iosDevices.devices 调用是异步的,在这种情况下,请参阅被标记为重复的问题,了解如何从异步调用中返回值。
    • 是的!最后,“如何从异步调用返回响应?”问题给了我解决问题的线索。非常感谢!
    猜你喜欢
    • 2022-01-27
    • 2018-03-22
    • 2022-01-16
    • 2020-03-07
    • 1970-01-01
    • 2020-03-16
    • 2018-07-29
    • 2022-12-17
    • 1970-01-01
    相关资源
    最近更新 更多