gpt4 book ai didi

node.js - 这个 promise 有什么问题?

转载 作者:行者123 更新时间:2023-12-03 12:17:02 24 4
gpt4 key购买 nike

作为练习,我正在尝试转换 https://developers.google.com/sheets/api/quickstart/nodejs从回调样式到 promises 样式,然后使用 util.promisify 将其重构为 async/await。

一切顺利,直到最终功能。原文是:

function listMajors(auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
console.log('Name, Major:');
// Print columns A and E, which correspond to indices 0 and 4.
rows.map((row) => {
console.log(`${row[0]}, ${row[4]}`);
});
} else {
console.log('No data found.');
}
});
}

promise 版本是:

function listMajors(auth) {
const sheets = google.sheets({version: 'v4', auth});

const getValues = util.promisify(sheets.spreadsheets.values.get);
getValues({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}).then(function (res) {
const rows = res.data.values;
if (rows.length) {
// Print columns A and E, which correspond to indices 0 and 4.
rows.map((row) => {
console.log(`${row[0]}, ${row[1]}`);
});
}
}).catch(err => console.log('The API returned an error: ' + err));
}

原件返回电子表格。 promise 版本说,API 返回错误:TypeError: Cannot read property 'context' of undefined。我不明白为什么它们不同。

最佳答案

您的 promisified 版本可能正在丢失您尝试调用的方法的父对象。

如果您将其更改为这个,则该问题应该得到解决:

let values = sheets.spreadsheets.values;
values.getP = util.promisify(sheets.spreadsheets.values.get);
values.getP().then(...);

这里重要的是,当调用你的 promisified 版本时,你仍在使用 values 对象引用,如 values.getP() 那样,promisified 函数仍然获取正确的 this 值。


仅供引用,您可能还可以将适当的对象绑定(bind)到方法:

const getValues = util.promisify(sheets.spreadsheets.values.get).bind(sheets.spreadsheets.values);

这里有一个简单的例子来演示:

class Test {
constructor() {
this.data = "Hello";
}

demo() {
console.log(this);
}
}


let t = new Test();

// this works just fine
t.demo();

// this doesn't work because x has lost the t object
// so when you call x(), it no longer has a reference to the object instance
// It needs to be called like obj.method()
let x = t.demo;
x();


这种情况经常出现,如果手边有这段代码就好了:

const util = require('util');
if (!util.promisifyMethod) {
util.promisifyMethod = function(fn, obj) {
return util.promisify(fn).bind(obj);
}
}

然后,任何时候你想 promise 某个对象的方法,你都可以使用它:

const getValues = util.promisifyMethod(sheets.spreadsheets.values.get, sheets.spreadsheets.values);

关于node.js - 这个 promise 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750247/

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