API调用和回调

时间:2018-10-30 20:41:00

标签: javascript node.js api express callback

我正在尝试创建一个进行2个API调用的路由,第二个路由取决于第一个API的结果,并且仅在满足某些条件时才需要调用。以下是我遇到的问题。

  1. 无论如何,finalCheck函数似乎都在forEach之前被调用。即使包裹在if语句中
  2. 该计数器和userNamesAvailable在范围之外不可用 他们被分配了。
  3. 我敢肯定,有更好的方法可以做到这一点,并且会喜欢任何相关的方法 建议。

    router.post('/namecheck', async function(req, res, next) {   
      var name = req.body.name;
      var counter = 0
      var domains = []
      var userNamesAvailable = []
      var dotcom = true
      var answer = ''
    
    getDomains(checkDomains)
    
    // Check domain availabilty
    function getDomains (callback) {
      var url='https://api.ote-godaddy.com/v1/domains/available?checkType=FAST'
      Unirest.post(url)
        .headers({
          "Authorization" : "sso-key ",
          "Content-Type": "application/json"
        })
        .send(
          [
            name + '.com',
            name + '.net',
            name + '.org'
          ]
        )
        .end(function(response) { 
          domains=response.body.domains
          console.log(domains)
          callback(domains)
        })
    
    }
     function checkDomains(domains) {
       var d = 0
    
    //If no data is returned send error
    if(!domains) 
    {
      console.log("No data returned")
      return next("No data returned")
    } else {
      //Check how many domains are unavailable
      for(var i=0; i < domains.length; i++) {
        if(domains[i].available == false){
          d = d + 1
          //Flag if the .com is available
          if(domains[i].domain == name + '.com') {
            dotcom = false
          }
        }
      }
    
      if (d >2) {
        console.log("d is greater than 1")
        answer = 'no'
      //If 2 domains are available and one is .com continue
      } else if (d>1 && dotcom =='false') {
        answer = 'no'
      }
    }
    getUsernames(finalCheck)
    }
    
    function getUsernames(callback){
      // Social Sites to Check
      var sitenames = [ 
        'facebook',
        'twitter',
        'instagram',
        'youtube',
        'slack',
        'blogger'
      ]
    
      // Check Usename availabitliy
      let i = 0
      sitenames.forEach(sitename => {
    
      Unirest.post('https://api.namechk.com/services/check.json')
      .headers({
        'AUTHORIZATION': 'Bearer ',
        'Accept': 'application/vnd.api.v1+json',
      }).send({
        'site': sitename, username: name,
      }).end(function(response) { 
        if(response.body.available == false){
          counter ++
        } else {
          userNamesAvailable.push(response.body)
        }
      });
      i++
    });
    console.log(counter)
    console.log(userNamesAvailable)
    if(i == sitenames.length){
      callback(counter, dotcom)
     }
    }
    
    function finalCheck(counter, dotcom) {
      console.log('Start finalCheck')
      console.log(counter)
      console.log(dotcom)
        //Final Check for is a name is a go or not
        //If one social site is not available and the 
        if(counter == 1 && dotcom =='true') {
          console.log(5-counter + ' social sites available')
          res.send("yes");
        } else {
          res.send("no")
        }
      }
     })
    

1 个答案:

答案 0 :(得分:2)

按照this question的答案进行操作。您应该可以使用Promise来做到这一点。

您只需要更改功能getUsernames

  function getUsernames(callback) {
    // Social Sites to Check
    var sitenames = [
      'facebook',
      'twitter',
      'instagram',
      'youtube',
      'slack',
      'blogger'
    ];

    // Check Usename availabitliy
    let requests = sitenames.map((sitename) => {
      return new Promise((resolve) => {
        Unirest.post('https://api.namechk.com/services/check.json')
          .headers({
            'AUTHORIZATION': 'Bearer ',
            'Accept': 'application/vnd.api.v1+json',
          }).send({
            'site': sitename,
            username: name,
          }).end(function(response) {
            if (response.body.available == false){
              counter++;
            } else {
              userNamesAvailable.push(response.body);
            }
            resolve();
          });
      });  
    });

    Promise.all(requests).then(() => { 
      console.log(userNamesAvailable);
      callback(counter, dotcom);
    });
  }

  function finalCheck() {
    console.log('Start finalCheck')
    console.log(counter)
    console.log(dotcom)
    //Final Check for is a name is a go or not
    //If one social site is not available and the
    if (counter == 1 & dotcom == 'true') {
      console.log(5 - counter + ' social sites available')
      res.send("yes");
    } else {
      res.send("no")
    }
  }

请记住,javascript中的异步功能是一项功能,而不是您应该使用的功能(我认为您正在尝试将主要功能声明为async function)。首先尝试了解它们,您会发现它们是一个很大的优势。

有很多关于它们的文档... async Fucntion understanding Promises

编辑:不要将调用 global 的变量作为参数发送,它们在调用的函数中已经可用。