在良好的云函数环境中,在request1调用内部,我能够获取bodydayOfTheWeek的输出。
但是在request1调用之外,我得到的输出未定义。
我不确定为什么。即使let变量bodydayOfTheWeek是在request1调用之外声明的。
因此不确定在请求调用中作用域变量如何工作
const request1 = require('request');
const url = 'http://worldclockapi.com/api/json/pst/now';
let bodydayOfTheWeek: any;
request1(url, { json: true }, (err: any, res: any, body: any) => {
if (err) { return console.log(err); }
console.log('inside day of the week');
bodydayOfTheWeek = body.dayOfTheWeek;
console.log(bodydayOfTheWeek); <-- works
});
console.log('outside day of the week');
console.log(bodydayOfTheWeek); <-- undefined
答案 0 :(得分:1)
(err: any, res: any, body: any) => { }
是异步的。因此,除非您通过回调/承诺得到bodydayOfTheWeek
,否则body.dayOfTheWeek
在函数外部将是未定义的。了解更多,https://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/
const request = require('request');
const url = 'http://worldclockapi.com/api/json/pst/now';
// Callback
function getDay(callback) {
request(url, { json: true }, (err: any, res: any, body: any) => {
if (err) {
return callback(err);
}
callback(null, body.dayOfTheWeek);
});
}
getDay((err, data) => {
console.log(data);
});
// Promise
function getDay() {
return new Promise((resolve, reject) => {
request(url, { json: true }, (err: any, res: any, body: any) => {
if (err) {
return reject(err);
}
resolve(body.dayOfTheWeek);
});
});
}
getDa().then((data) => {
console.log(data);
});