-
Notifications
You must be signed in to change notification settings - Fork 2.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Return Promise if callback is not provided? #1515
Comments
Historically, However, with the new |
I've thought about this, and experimented with it a bit. People are going to want to Also, some Async methods would be pretty silly with async/await, e.g. |
When using Async I sort of naturally assumed the return of a Promise. It was only at the dis-functioning of my code and my routine rtfm moment that I noticed the callback structure. The above would be very welcome since it would keep code as uniform ES7 as possible. |
I agree that this would be useful. In the interim, if anyone is stuck right now, I found this article good for explaining how to write a forEach loop with await. |
Finally dug out my old experiment: #1526 |
+1 |
function makeAsync() {
if (arguments.length < 3) return; // wrong params, not run or throw exception here!
let fixParams = {};
let paramLength = arguments.length;
let method = arguments[0];
for (let i = 1; i < arguments.length; i++) {
fixParams[(i - 1)] = arguments[i];
}
return new Promise((resolve, reject) => {
const callback = (err, result) => {
if (err) return reject(err);
return resolve(result);
};
fixParams[paramLength - 1] = callback;
fixParams.length = paramLength;
method.apply(null, fixParams);
});
} example1: await makeAsync(async.each, openFiles, async (file) => {
await asyncOperation(file);
}); example2: const foo = async () => {
const arr = Array.from({ length: 1000 }, (v, i) => i);
const transformedArr = await makeAsync(async.mapLimit, arr, 100, async (v) => {
return await Promise.resolve(v * 2);
});
console.log(transformedArr);
} |
@tritoanst, your promisify function is overhead. It may be easier: function promisify(original) {
return function (...args) {
return new Promise((resolve, reject) => {
args.push((err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
original.apply(this, args);
});
};
}
const foo = async () => {
const arr = Array.from({ length: 1000 }, (v, i) => i);
const transformedArr = await promisify(async.mapLimit)(arr, 100, async (v) => {
return v * 2; // `return await` is redundant
});
console.log(transformedArr);
}; |
Nice to have in ES2017 async/await development
The text was updated successfully, but these errors were encountered: