我正在尝试将ES2018 async
功能转换为ES2015(ES6)功能,但是我得到了超时,猜测我的ES2015版本错了......但是在哪里?
ES2018版本
async function connectGoogleAPI () {
// Create a new JWT client using the key file downloaded from the Google Developer Console
const client = await google.auth.getClient({
keyFile: path.join(__dirname, 'service-key.json'),
scopes: 'https://www.googleapis.com/auth/drive.readonly'
});
// Obtain a new drive client, making sure you pass along the auth client
const drive = google.drive({
version: 'v2',
auth: client
});
// Make an authorized request to list Drive files.
const res = await drive.files.list();
console.log(res.data);
return res.data;
}
ES2015版本w / Promise
function connectGoogleAPI () {
return new Promise((resolve, reject) => {
const authClient = google.auth.getClient({
keyFile: path.join(__dirname, 'service-key.json'),
scopes: 'https://www.googleapis.com/auth/drive.readonly'
});
google.drive({
version: 'v2',
auth: authClient
}), (err, response) => {
if(err) {
reject(err);
} else {
resolve(response);
}
}
});
}
答案 0 :(得分:4)
您尚未翻译await
getClient
。请记住,await
= then
(粗略地)。您还会成为promise creation anti-pattern的牺牲品:当您已经有一个承诺(来自getClient
)时,您几乎不需要使用new Promise
。只需使用then
。
以下是将await
转换为then
的示例,并使用该链进行后续操作:
function connectGoogleAPI () {
// Create a new JWT client using the key file downloaded from the Google Developer Console
return google.auth.getClient({
keyFile: path.join(__dirname, 'service-key.json'),
scopes: 'https://www.googleapis.com/auth/drive.readonly'
}).then(client => {
// Obtain a new drive client, making sure you pass along the auth client
const drive = google.drive({
version: 'v2',
auth: client
});
// Make an authorized request to list Drive files.
return drive.files.list();
}).then(res => {
console.log(res.data);
return res.data;
});
}
最后一部分可以只是
}).then(res => res.data);
...如果您删除了console.log
。 (或者我们可以滥用逗号运算符。)
注意:
await
都需要成为then
处理程序(原始版本中有两个,等待getClient
和drive.files.list
)then
处理程序中,如果您必须等待另一个承诺(例如来自drive.files.list
的承诺),您通常从处理程序返回,然后使用另一个处理 结果的处理程序(这就是为什么我有return drive.files.list()
然后是一个单独的处理程序,用于将res
转换为res.data
)重申第二点:有时嵌套是合适的,例如当您需要将结果与您在then
处理程序中只有的某个中间值组合时。 (例如,如果我们想将res.data
与client
结合起来。)但通常情况下,不要嵌套。