如何将谷歌OAuth授权回调包装在承诺中?



我把一个google nodejs快速入门示例作为如何做oauth的模型,把它重写为类对象,这样我就可以把它包含在我更大的项目中。我可以成功运行应用程序脚本 api 调用 scripts.run 并在类对象中获取有效的返回值,但不能成功运行如何将其返回到包含的项目。

scripts.run 包含函数看起来像这样

Goo.prototype.testAuth = function( auth ){
var script = google.script('v1');
var cmd = {
auth,
resource: { function: 'test_auth', devMode: true },
scriptId: '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
};
script.scripts.run(
cmd,
function( err, resp ){
if( err ){ console.log('The API returned an error: ' + err);return }
if( resp.error ){console.log('Script error message: '
+ resp.error.details[0].error.errorMessage);}
else {
console.log('resp from api call', resp.response.result );
return resp.response.result ;
}
});
};

返回响应.结果是有问题的部分,因为它没有传递回容器中的var 响应

var Goo = require('./Goo.js');
var goo = new Goo();
var response = goo.test_auth();
console.log('response to use elsewhere ',response);

众所周知,Goo 类中的控制台.log返回一个值.log而容器中的控制台返回 undefined。

所有的Goo类都像这样结束,如果这很重要的话

(function(){
var Goo = (function(){
var Goo = function(config){
}
Goo.prototype.test_auth = function(){
this.authorize( this.testAuth );
};
Goo.prototype.testAuth = function(){};
Goo.prototype.authorize = function(){};
})();
module.exports = Goo;
})();

我应该如何构建它以返回要在容器中使用的值?

我不清楚我是否应该尝试将 script.scripts.run 包装在一个承诺中,如果它已经返回了一个承诺并且我不知道如何等待它的返回,或者我正在处理回调函数的事实是否使它成为错误的解决方案。感谢此处的任何指导。

我正在使用node.js和googleapis ^24.0.0

testAuth函数不返回当前写入的任何内容。 人们可以像下面这样"承诺"它......

Goo.prototype.testAuth = function( auth ){
return new Promise((resolve, reject) => {
var script = google.script('v1');
var cmd = {
auth,
resource: { function: 'test_auth', devMode: true },
scriptId: '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
};
script.scripts.run(
cmd,
function( err, resp ){
if( err ){
console.log('The API returned an error: ' + err);
reject(err);
} else if( resp.error ){
console.log('Script error message: ' + resp.error.details[0].error.errorMessage);
reject(resp.error);
} else {
console.log('resp from api call', resp.response.result );
resolve(resp.response.result);
}
});
});
};

然后这样称呼它...

var Goo = require('./Goo.js');
var goo = new Goo();
goo.test_auth().then(response => {
console.log('response to use elsewhere ',response);
}).catch(error => {
console.log('error ',error);
});

抱歉,缩进格式有点奇怪。 OP 使用 3 个空格进行缩进,而不是通常的 2 个或 4 个空格。 (自我注意:下一集"硅谷"的想法(

最新更新