Skip to content

Commit 2cd7fe3

Browse files
author
chenyumic
authored
Updated select samples to use async/await. (#1012)
* Updated select samples to use async/await. * Minor fixes. * Minor fixes. * Completed requested changes.
1 parent a0a4472 commit 2cd7fe3

File tree

6 files changed

+59
-56
lines changed

6 files changed

+59
-56
lines changed

appengine/analytics/app.js

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,25 @@ function trackEvent(category, action, label, value) {
5050
return got.post('http://www.google-analytics.com/collect', data);
5151
}
5252

53-
app.get('/', (req, res, next) => {
53+
app.get('/', async (req, res, next) => {
5454
// Event value must be numeric.
55-
trackEvent('Example category', 'Example action', 'Example label', '100')
56-
.then(() => {
57-
res
58-
.status(200)
59-
.send('Event tracked.')
60-
.end();
61-
})
55+
try {
56+
await trackEvent(
57+
'Example category',
58+
'Example action',
59+
'Example label',
60+
'100'
61+
);
62+
res
63+
.status(200)
64+
.send('Event tracked.')
65+
.end();
66+
} catch (error) {
6267
// This sample treats an event tracking error as a fatal error. Depending
6368
// on your application's needs, failing to track an event may not be
6469
// considered an error.
65-
.catch(next);
70+
next(error);
71+
}
6672
});
6773

6874
const PORT = process.env.PORT || 8080;

appengine/datastore/app.js

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -53,15 +53,10 @@ function getVisits() {
5353
.order('timestamp', {descending: true})
5454
.limit(10);
5555

56-
return datastore.runQuery(query).then(results => {
57-
const entities = results[0];
58-
return entities.map(
59-
entity => `Time: ${entity.timestamp}, AddrHash: ${entity.userIp}`
60-
);
61-
});
56+
return datastore.runQuery(query);
6257
}
6358

64-
app.get('/', (req, res, next) => {
59+
app.get('/', async (req, res, next) => {
6560
// Create a visit record to be stored in the database
6661
const visit = {
6762
timestamp: new Date(),
@@ -73,17 +68,21 @@ app.get('/', (req, res, next) => {
7368
.substr(0, 7),
7469
};
7570

76-
insertVisit(visit)
77-
// Query the last 10 visits from Datastore.
78-
.then(() => getVisits())
79-
.then(visits => {
80-
res
81-
.status(200)
82-
.set('Content-Type', 'text/plain')
83-
.send(`Last 10 visits:\n${visits.join('\n')}`)
84-
.end();
85-
})
86-
.catch(next);
71+
try {
72+
await insertVisit(visit);
73+
const results = await getVisits();
74+
const entities = results[0];
75+
const visits = entities.map(
76+
entity => `Time: ${entity.timestamp}, AddrHash: ${entity.userIp}`
77+
);
78+
res
79+
.status(200)
80+
.set('Content-Type', 'text/plain')
81+
.send(`Last 10 visits:\n${visits.join('\n')}`)
82+
.end();
83+
} catch (error) {
84+
next(error);
85+
}
8786
});
8887

8988
const PORT = process.env.PORT || 8080;

appengine/metadata/standard/server.js

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -31,26 +31,23 @@ function getProjectId() {
3131
},
3232
};
3333

34-
return request(METADATA_PROJECT_ID_URL, options)
35-
.then(response => response.body)
36-
.catch(err => {
37-
if (err && err.statusCode !== 200) {
38-
console.log('Error while talking to metadata server.');
39-
return 'Unknown_Project_ID';
40-
}
41-
return Promise.reject(err);
42-
});
34+
return request(METADATA_PROJECT_ID_URL, options);
4335
}
4436

45-
app.get('/', (req, res, next) => {
46-
getProjectId()
47-
.then(projectId => {
48-
res
49-
.status(200)
50-
.send(`Project ID: ${projectId}`)
51-
.end();
52-
})
53-
.catch(next);
37+
app.get('/', async (req, res, next) => {
38+
try {
39+
let response = await getProjectId();
40+
let projectId = response.body;
41+
res
42+
.status(200)
43+
.send(`Project ID: ${projectId}`)
44+
.end();
45+
} catch (error) {
46+
if (error && error.statusCode && error.statusCode !== 200) {
47+
console.log('Error while talking to metadata server.');
48+
}
49+
next(error);
50+
}
5451
});
5552

5653
const PORT = process.env.PORT || 8080;

appengine/pubsub/app.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,28 +44,28 @@ const messages = [];
4444
// The following environment variables are set by app.yaml when running on GAE,
4545
// but will need to be manually set when running locally.
4646
const PUBSUB_VERIFICATION_TOKEN = process.env.PUBSUB_VERIFICATION_TOKEN;
47+
const TOPIC = process.env.PUBSUB_TOPIC;
4748

48-
const topic = pubsub.topic(process.env.PUBSUB_TOPIC);
49-
const publisher = topic.publisher();
49+
const publisher = pubsub.topic(TOPIC).publisher();
5050

5151
// [START gae_flex_pubsub_index]
5252
app.get('/', (req, res) => {
5353
res.render('index', {messages: messages});
5454
});
5555

56-
app.post('/', formBodyParser, (req, res, next) => {
56+
app.post('/', formBodyParser, async (req, res, next) => {
5757
if (!req.body.payload) {
5858
res.status(400).send('Missing payload');
5959
return;
6060
}
6161

62-
publisher.publish(Buffer.from(req.body.payload), err => {
63-
if (err) {
64-
next(err);
65-
return;
66-
}
67-
res.status(200).send('Message sent');
68-
});
62+
let data = Buffer.from(req.body.payload);
63+
try {
64+
let messageId = await publisher.publish(data);
65+
res.status(200).send(`Message ${messageId} sent.`);
66+
} catch (error) {
67+
next(error);
68+
}
6969
});
7070
// [END gae_flex_pubsub_index]
7171

appengine/pubsub/app.standard.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
# Copyright 2015-2016, Google, Inc.
23
# Licensed under the Apache License, Version 2.0 (the "License");
34
# you may not use this file except in compliance with the License.

appengine/pubsub/test/app.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ test.serial.cb(`should send a message to Pub/Sub`, t => {
3535
.send({payload: payload})
3636
.expect(200)
3737
.expect(response => {
38-
t.is(response.text, `Message sent`);
38+
t.regex(response.text, /Message \d* sent/);
3939
})
4040
.end(t.end);
4141
});

0 commit comments

Comments
 (0)