node.js - Nodejs执行函数
问题描述
我是 Nodejs 的新手,想知道为什么函数会乱序执行,而不是我是如何编写的:
var tor_proxy = require("tor-request")
var s = require("sleep");
tor_proxy.setTorAddress("localhost", 9050);
tor_proxy.TorControlPort.password = "password";
function ShowIP() {
tor_proxy.request("http://ident.me", function(err, response, body) {
if(!err && response.statusCode == 200) {
console.log(body);
}
});
}
function Renew() {
tor_proxy.renewTorSession(function() { console.log("renewed"); });
}
ShowIP();
Renew();
ShowIP();
//Id Like It To Show The IP Then Renew Then Show The New IP
//But Instead It's Out Of Order
Nodejs 是事件驱动的(如果我错了,请纠正我),任何帮助将不胜感激。谢谢 :)
解决方案
该脚本将像这样执行:
- 在里面
ShowIP()
,向http://ident.metor_proxy.request()
发送一个请求。 - 无需等待来自http://ident.me的任何回复,函数
Renew()
就会被执行。 tor_proxy.renewTorSession()
很可能是一个异步函数。如果是这样,则在它开始后,ShowIP()
将执行下一个,而无需等待renewTorSession()
完成。
根据http://ident.me回复的速度和renewTorSession()
完成的速度,结果可能会有所不同。
要按正确顺序执行这些功能,您可以搜索以下关键字:
Promise
Async
/Await
- 来自 Node.js 的util.promisify()
- 像Async.js这样的库
promise
使用,async
和的示例await
:
var tor_proxy = require('tor-request');
tor_proxy.setTorAddress('localhost', 9050);
tor_proxy.TorControlPort.password = 'password';
function ShowIP() {
return new Promise((resolve, reject) => {
tor_proxy.request('http://ident.me', function (err, response, body) {
if (err) reject(err);
else if (response.statusCode !== 200) reject('response.statusCode: ' + response.statusCode);
else {
console.log(body);
resolve();
}
});
});
}
function Renew() {
return new Promise((resolve, reject) => {
tor_proxy.renewTorSession(() => {
console.log('renewed');
resolve();
});
});
}
async function testFunction() {
// Await makes sure the returned promise completes before proceeding.
// Note that await keyword can only be used inside async function.
try {
await ShowIP();
await Renew();
await ShowIP();
console.log('done!');
} catch (error) {
console.log(error);
}
}
testFunction();
推荐阅读
- css - 更改 Kendo React UI 的主题
- c - 垂直于传感器的矢量相对于垂直于地球的矢量的角度
- java - 如何在 Blaze Persistence 查询上实现多个根实体?
- javascript - 如何使用 javascript 请求音频自动播放权限
- node.js - 如何在 NodeJS 中使用与 python 中的 splitlines() 类似的东西
- amazon-web-services - AWS Inspector 生成的审计任务是否应该在正在进行的生产服务器上执行?
- javascript - 如何在反应中使用上下文 api 将数据从子组件更新到父组件?
- snowflake-cloud-data-platform - SnowFlake 查询处理时间复杂度
- bash - 无法使用 Jenkins 在 ssh bash 中获取先前的状态命令
- linux - 如何获取按时间顺序调用的所有函数的列表?