【发布时间】:2018-11-01 06:21:29
【问题描述】:
我正在尝试将 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;
}
带有 Promise 的 ES2015 版本
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);
}
}
});
}
【问题讨论】:
-
... 但是
Promise是 ES6 标准功能,所以在您的 ES5 版本中您实际上使用了库?而async是 ES7+,而不是 ES6,你的意思是 ES6 还是 ES7? -
您的版本错误。 :-) Promise 是 ES2015(也称为“ES6”)。
async/await是 ES2018。 -
google.auth.getClient()使用什么库? -
在您的 ES6 版本中,您是
awaitinggoogle.auth.getClient(),但在 ES5 版本中,您没有对google.auth.getClient()的回调。 -
(我已经为你修复了版本。)
标签: ecmascript-6 promise async-await