Nodejs执行功能

时间:2018-11-20 23:12:24

标签: node.js function asynchronous

我是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是事件驱动的(如果我错了,请纠正我),我们将不胜感激。谢谢:)

1 个答案:

答案 0 :(得分:2)

脚本将像这样执行:

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

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

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

使用promiseasyncawait的示例:

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