Converting a old style callback style function into a async-await one

callback style:

callback style function is a function or method you call with some data and a callback function. The first argument of the callback function is usually the error. If the result of the call does not have error, the error argument will be null or undefined. Here is example from AWS SDK:

s3.putObject(params, function (err) {
});
fs.readFile('/foo.txt', function(err, data) {
});

promise style function:

fetch('url').then(res => {
return res.json();
}).then(json => {
console.log(json);
}).catch(err => {
console.log(err);
})

async-await style

The same code above can be written as:

try {
const res = await fetch('url');
const json = await res.json();
console.log(json);
} catch (err) {
console.log(err);
}
try {
const res = await fetch('url');
const json = await res.json();
console.log(json);
+ await asyncFunc1();
+ await asyncFunc2();
...
} catch (err) {
console.log(err);
}

Converting a callback style function to async-await one

Because we can use use await on any functions that return a promise object, we can create a function that return a promise with the callback style function. So we can convert this callback style function from this:

s3.putObject(params, function (err) {
});
const putObject = async (params) => {
return new Promise((resolve, reject) => {
s3.putObject(params, function (err) {
if (err) return reject(err);
resolve();
});
})
}
await putObject(params);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store