函数 returns 在完成她的工作之前
Function returns before completing her job
我已经编写了这个函数,它 return 是在完成她的工作之前的值。所以 return 总是 undefined
。我怎样才能得到正确的结果?
代码:
async function isReachable(hostname, port) {
net
.connect(port, hostname, () => {
console.log(true);
return true;
})
.on('error', () => {
console.log(false);
return false;
});
}
日志:
Promise { undefined }
true
谢谢:)
将方法的开头更改为:
async function isReachable(hostname, port) {
return net
.connect(
...
您缺少 return
,您将获得默认 undefined
return。
isReachable
然后 return 一个 Promise
你可以 await
结果
如果 net.connect() 不是 return Promise,您需要将函数实现包装在 Promise 中,并使用 resolve() 回调 return true/false 在 .connect() 和 .on() 回调函数中。
function isReachable(hostname, port) {
return new Promise(
(resolve, reject) => {
net
.connect(port, hostname, () => {
resolve(true);
})
.on('error', () => {
resolve(false);
});
}
);
}
如果净 returns 一个承诺,对我来说,正确的解决方案应该包含 'await' 的 'async' accros。看看 doc:
The advantage of an async function only becomes apparent when you combine it with the await keyword. await only works inside async functions within regular JavaScript code, however it can be used on its own with JavaScript modules.
await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.
像这样:
async function isReachable(hostname, port) {
return netResults = await net
.connect(port, hostname, () => {
console.log(true);
return true;
})
.on('error', () => {
console.log(false);
return false;
});
}
我已经编写了这个函数,它 return 是在完成她的工作之前的值。所以 return 总是 undefined
。我怎样才能得到正确的结果?
代码:
async function isReachable(hostname, port) {
net
.connect(port, hostname, () => {
console.log(true);
return true;
})
.on('error', () => {
console.log(false);
return false;
});
}
日志:
Promise { undefined }
true
谢谢:)
将方法的开头更改为:
async function isReachable(hostname, port) {
return net
.connect(
...
您缺少 return
,您将获得默认 undefined
return。
isReachable
然后 return 一个 Promise
你可以 await
结果
如果 net.connect() 不是 return Promise,您需要将函数实现包装在 Promise 中,并使用 resolve() 回调 return true/false 在 .connect() 和 .on() 回调函数中。
function isReachable(hostname, port) {
return new Promise(
(resolve, reject) => {
net
.connect(port, hostname, () => {
resolve(true);
})
.on('error', () => {
resolve(false);
});
}
);
}
如果净 returns 一个承诺,对我来说,正确的解决方案应该包含 'await' 的 'async' accros。看看 doc:
The advantage of an async function only becomes apparent when you combine it with the await keyword. await only works inside async functions within regular JavaScript code, however it can be used on its own with JavaScript modules.
await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.
像这样:
async function isReachable(hostname, port) {
return netResults = await net
.connect(port, hostname, () => {
console.log(true);
return true;
})
.on('error', () => {
console.log(false);
return false;
});
}