从ES2018 async / await到ES2015 Promises。 ... 超时

时间:2018-05-22 13:01:24

标签: ecmascript-6 promise async-await

我正在尝试将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);
          }
        }
      });
    }

1 个答案:

答案 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处理程序(原始版本中有两个,等待getClientdrive.files.list
  • then处理程序中,如果您必须等待另一个承诺(例如来自drive.files.list的承诺),您通常从处理程序返回,然后使用另一个处理 结果的处理程序(这就是为什么我有return drive.files.list()然后是一个单独的处理程序,用于将res转换为res.data

重申第二点:有时嵌套是合适的,例如当您需要将结果与您在then处理程序中只有的某个中间值组合时。 (例如,如果我们想将res.dataclient结合起来。)但通常情况下,不要嵌套。