早上好!
我一直在努力从我的函数中返回一个特定的值:
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()
}
这可能吗?如果是这样,如何?
谢谢!
通常有三种方法处理异步内容:
- 回调
- 承诺
- 异步/等待
回调:
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 实际上是一种语法糖,getFolders
函数与使用 promise 相同,区别在于调用它时:
(async function() {
try {
let v = await getFolders(pid)
console.log(v)
} catch(e) {
console.error(e)
}
})()
不确定这是否能解决您的困惑。
你期望的方式是错误的,你传递给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)
}