Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使nodejs中的函数同步_Node.js - Fatal编程技术网

Node.js 如何使nodejs中的函数同步

Node.js 如何使nodejs中的函数同步,node.js,Node.js,我做了这个函数,从Aviationstack API(一个飞行API)检索飞行数据。我是nodejs新手,我想使用“sync request”使这个函数同步,这样当我在任何地方调用时,我都可以得到一些回报。以下是功能代码: function get_flights_by_date(date) { let url = 'http://api.aviationstack.com/v1/flights?access_key=xxxxxxxxxxxxxxxxx&

我做了这个函数,从Aviationstack API(一个飞行API)检索飞行数据。我是nodejs新手,我想使用“sync request”使这个函数同步,这样当我在任何地方调用时,我都可以得到一些回报。以下是功能代码:

    function get_flights_by_date(date) { 
      
      let url = 'http://api.aviationstack.com/v1/flights?access_key=xxxxxxxxxxxxxxxxx&flight_status=scheduled'
     
      request(url, function (err, response, body) {
        if (err) {
          console.log('error:', error);
        } else {
          let vol = JSON.parse(body)
          num = vol.pagination.limit
          for (let i = 0; i < num; i++) {
            dep = vol.data[i].departure.airport
            depart = vol.data[i].departure.timezone
            arrival = vol.data[i].arrival.timezone
            arr = vol.data[i].arrival.airport
            flight_date = vol.data[i].flight_date
            number = vol.data[i].flight.number
             console.log('flight number:' + ' ' + number + ' ' + 'from' + ' ' + depart + ' ' + 'at' + ' ' + dep + ' ' + 'airport' + ' ' + 'to' + ' ' + arrival + ' ' + 'at' + ' ' + arr + ' ' + 'airport' + ' ' + 'on' + ' ' + flight_date + '.')
            
          }
        }

  });
  
}
函数按日期获取航班(日期){
让url为空http://api.aviationstack.com/v1/flights?access_key=xxxxxxxxxxxxxxxxx&flight_status=scheduled'
请求(url、函数(错误、响应、正文){
如果(错误){
console.log('error:',error);
}否则{
让vol=JSON.parse(body)
num=vol.pagination.limit
for(设i=0;i
如果可能的话,我会完全避免使用同步代码,因为这不会扩展。这是一种非常糟糕的做法,只要请求仍在获取,服务器就会停止

您可以(也应该)使用
async
/
wait
,或
Promise
在确保服务器可用的同时等待数据

如果您想避免
,那么
Promise上的
回调
,只需使用
异步
/
等待

转换为使用
Promise
async
/
wait

function get_flights_by_date(date) { 
  const url = 'http://api.aviationstack.com/v1/flights?access_key=xxxxxxxxxxxxxxxxx&flight_status=scheduled'
  return new Promise((resolve, reject) => {
    request(url, (err, response, body) => {
      if (err) {
        reject(err);
      } else {        
        const data = JSON.parse(body); // Process your data
        resolve(data);
      }
    });
  })
}

function promiseExample() {
  get_flights_by_date(new Date()).then(resultData => console.log(resultData))
}

async function example() {
  const resultData = await get_flights_by_date(new Date());
  console.log(resultData);
}

这不是在node js中生成同步代码的方法

很少有方法使任何代码同步

  • 回拨

    当您直接从其他函数调用时,您正在执行的操作将失败。相反,你可以这样做

     function get_flights_by_date(date, callback) { 
    
      let url = 'http://api.aviationstack.com/v1/flights?access_key=xxxxxxxxxxxxxxxxx&flight_status=scheduled'
    
      request(url, function (err, response, body) {
        if (err) {
          console.log('error:', error);
          callback(err);
        } else {
          let vol = JSON.parse(body)
          num = vol.pagination.limit
          for (let i = 0; i < num; i++) {
            dep = vol.data[i].departure.airport
            depart = vol.data[i].departure.timezone
            arrival = vol.data[i].arrival.timezone
            arr = vol.data[i].arrival.airport
            flight_date = vol.data[i].flight_date
            number = vol.data[i].flight.number
             console.log('flight number:' + ' ' + number + ' ' + 'from' + ' ' + depart + ' ' + 'at' + ' ' + dep + ' ' + 'airport' + ' ' + 'to' + ' ' + arrival + ' ' + 'at' + ' ' + arr + ' ' + 'airport' + ' ' + 'on' + ' ' + flight_date + '.')
    
          }
          callback(null, number)
        }
     });}
     function mainFunction(){
        var date = '';
        get_flights_by_date(date, function(err, result){
            if(err){
                return err
            }
            return result
        })
    }
    
    函数按日期获取航班(日期,回调){
    让url为空http://api.aviationstack.com/v1/flights?access_key=xxxxxxxxxxxxxxxxx&flight_status=scheduled'
    请求(url、函数(错误、响应、正文){
    如果(错误){
    console.log('error:',error);
    回调(err);
    }否则{
    让vol=JSON.parse(body)
    num=vol.pagination.limit
    for(设i=0;i
  • 允诺

    function get_flights_by_date(date) {
      return new Promise(function (resolve, reject) {
    let url =
      "http://api.aviationstack.com/v1/flights?access_key=xxxxxxxxxxxxxxxxx&flight_status=scheduled";
    
    request(url, function (err, response, body) {
      if (err) {
        console.log("error:", error);
        reject(err);
      } else {
        let vol = JSON.parse(body);
        num = vol.pagination.limit;
        for (let i = 0; i < num; i++) {
          dep = vol.data[i].departure.airport;
          depart = vol.data[i].departure.timezone;
          arrival = vol.data[i].arrival.timezone;
          arr = vol.data[i].arrival.airport;
          flight_date = vol.data[i].flight_date;
          number = vol.data[i].flight.number;
        }
        resolve(number);
      }
    });});
    }
    async function main() {
      try {
        await get_flights_by_date("");
      } catch (error) {}
    }
    
    函数按日期获取航班(日期){
    返回新承诺(功能(解决、拒绝){
    让url=
    "http://api.aviationstack.com/v1/flights?access_key=xxxxxxxxxxxxxxxxx&flight_status=scheduled";
    请求(url、函数(错误、响应、正文){
    如果(错误){
    日志(“错误:”,错误);
    拒绝(错误);
    }否则{
    让vol=JSON.parse(body);
    num=vol.pagination.limit;
    for(设i=0;i
  • 异步库

  • 或者您也可以使用这个库在这里完成整个代码

    我建议您选择异步lib,因为它很容易以这种方式进行扩展