如何将以下代码转换为异步等待

时间:2018-10-18 18:31:15

标签: node.js google-cloud-datastore

const {Resource} = require('@google-cloud/resource');
const projectId = 'YOUR_PROJECT_ID';
const resourceClient = new Resource({
  projectId: projectId,
});

resourceClient
  .getProjects()
  .then(results => {
    const projects = results[0];
    console.log('Projects:');
    projects.forEach(project => console.log(project.id));
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

我需要将此代码转换为asyncawait。我该怎么办?

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要创建一个异步函数才能使用async-await。

也许是这样的:

const {Resource} = require('@google-cloud/resource')
const projectId = 'YOUR_PROJECT_ID'
const resourceClient = new Resource({
  projectId: projectId,
})

const run = async () => {
  try {
    const results = await resourceClient.getProjects()
    const projects = results[0]
    console.log('Projects:')
    projects.forEach(project => console.log(project.id))
  }
  catch(err) {
    console.error('ERROR:', err)
  }
}

run()