gpt4 book ai didi

javascript - Node.js 从匿名函数访问值

转载 作者:行者123 更新时间:2023-12-01 00:14:42 24 4
gpt4 key购买 nike

早上好!

我一直在努力从我的函数返回一个特定的值:

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

这可能吗?如果是这样,怎么办?

谢谢!

最佳答案

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

  • 回调
  • promise
  • 异步/等待

回调:

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)
})

promise :

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

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

关于javascript - Node.js 从匿名函数访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59846024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com