Javascript 承诺在未定义的情况下得到解决
我试图理解promises和async Wait是如何工作的,我构建了以下代码来获取计算机上已连接设备的列表,但它返回“undefined”Javascript 承诺在未定义的情况下得到解决,javascript,node.js,async-await,promise,Javascript,Node.js,Async Await,Promise,我试图理解promises和async Wait是如何工作的,我构建了以下代码来获取计算机上已连接设备的列表,但它返回“undefined” var iosDevice = require("node-ios-device"); const the_action = () => { iosDevice.devices(function (err, devices) { if (err) { console.error("Error!&
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);
我正在使用节点从终端运行上述脚本:
$>将_script.js作为节点
我做错了什么或错过了什么
提前感谢您
操作
没有返回任何内容。return语句只是从iosDevice.devices
回调返回,但包含的函数不返回任何内容。这就是你的问题所在。如果您得到返回某物的操作
,它将通过您的承诺解决方案冒泡出来,并最终得到控制台。登录感谢您的回答,根据您的建议更新代码:让conn\u dev;const the_action=()=>{iosDevice.devices(函数(err,devices){if(err){console.error(“error!”,err);}否则{conn_dev=devices;}}});return conn_dev}
导致相同的“未定义”result@viking_biking这一定意味着您的iosDevices.devices调用是异步的,在这种情况下,请参阅标记为重复的问题,了解如何从异步调用返回值。是!,最后,“如何从异步调用返回响应?”这个问题为我提供了解决问题的线索。非常感谢你!