Node.js 从匿名函数访问值

Node.js Access Values from Anonymous function

早上好!

我一直在努力获取函数返回的特定值:

const getFolders = function (PID){
var token = getStoredToken()
request.get({
    url: 'https://api.procore.com/vapid/folders',
    headers: {
        Authorization: "Bearer " + token.access_token
    }, 
    json: {
        company_id: '12594',
        project_id: PID
    }
}, function test(err, response, body){
    return body
})
// I NEED THE RETURN VALUE OF THE ABOVE FUNCTION HERE SO I CAN ACCESS WHEN CALLING getFolders()
}

这可能吗?如果可以,怎么做?

谢谢!

你期望的方式是错误的,你传递给 request.get 方法的测试函数是一个回调函数,它将以异步方式执行,这意味着每当你的 API 从服务器,该回调函数将被执行。

所以在此之前你期望响应(正文)低于请求方法,这是错误的。

在这种情况下,您只需编写一些其他函数来调用此 get 方法,并且在回调函数中您可以轻松访问该响应或仅在该测试函数本身中编写代码。

喜欢下面 - :

request.get({
    url: 'https://api.procore.com/vapid/folders',
    headers: {
        Authorization: "Bearer " + token.access_token
    }, 
    json: {
        company_id: '12594',
        project_id: PID
    }
}, function test(err, response, body){
   // instead of returning body
   // use the body here only
   let result = body;

   // your code here
})

或者反过来-:

const getFolders = function (PID){
var token = getStoredToken();
this.get(function(err, response, body){
    // do whatever you want with the response now
      updateFolder()
})
}

function get(callback){
    request.get({
    url: 'https://api.procore.com/vapid/folders',
    headers: {
        Authorization: "Bearer " + token.access_token
    }, 
    json: {
        company_id: '12594',
        project_id: PID
    }
}, callback)
}

通常有三种处理异步内容的方法:

  • 回调
  • 承诺
  • async/await

回调:

const getFolders = function(PID, callback) {
  var token = getStoredToken()
  request.get({
    url: 'https://api.procore.com/vapid/folders',
    headers: {
      Authorization: "Bearer " + token.access_token
    },
    json: {
      company_id: '12594',
      project_id: PID
    }
  }, function(err, response, body) {
    callback(body)
  })
}

getFolders(pid, (v) => {
  console.log(v)
})

承诺:

const getFolders = function(PID, callback) {
  return new Promise((resolve, reject) => {
    var token = getStoredToken()
    request.get({
      url: 'https://api.procore.com/vapid/folders',
      headers: {
        Authorization: "Bearer " + token.access_token
      },
      json: {
        company_id: '12594',
        project_id: PID
      }
    }, function(err, response, body) {
      if (err) {
        return reject(err)
      }
      resolve(body)
    })
  })
}

getFolders(pid)
  .then(v => {
    console.log(v)
  }).catch(error => {
    console.error(error)
  })

async/await: 由于async/await其实是一个语法糖,所以getFolders的功能和使用promise的一样,区别在于调用的时候:

(async function() {
  try {
    let v = await getFolders(pid)
    console.log(v)
  } catch(e) {
    console.error(e)
  }
})()

不确定这是否能解决您的困惑。