首页 > 解决方案 > 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 是事件驱动的(如果我错了,请纠正我),任何帮助将不胜感激。谢谢 :)

标签: node.jsfunctionasynchronous

解决方案


该脚本将像这样执行:

  1. 在里面ShowIP(),向http://ident.metor_proxy.request()发送一个请求。
  2. 无需等待来自http://ident.me的任何回复,函数Renew()就会被执行。
  3. tor_proxy.renewTorSession()很可能是一个异步函数。如果是这样,则在它开始后,ShowIP()将执行下一个,而无需等待renewTorSession()完成。

根据http://ident.me回复的速度和renewTorSession()完成的速度,结果可能会有所不同。

要按正确顺序执行这些功能,您可以搜索以下关键字:

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();

推荐阅读