async function equivalent of a Promise
I have a function that returns a promise
like this:
let aFunction= function(){
return new Promise((resolve, reject){
someNodeApi(params, function(err, data)) {
if(err) {
return reject(err);
}
if(data meets certain criteria) {
someOtherNodeApi(params, function(err, data)) {
// handle conditions.
}
}
resolve(data);
}
})
}
I want to have an async
function equivalent for this kind of function. In short, I need something like this:
let aFunction = async function(){
someNodeApi(params, function(err, data){
if(err) {
// reject condition
}
// resolve condition.
})
}
So what should be in above reject
and resolve
conditions so that all the places where I call the function like this:
aFunction()
.then(data=>{})
.catch(err=>{})
It should be unchanged.
EDIT
I have to clarify that my question is not about how to call the async function. But its about how to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called. (A very common scenario when you are dealing with pre async-await era node js code).
javascript node.js promise async-await
|
show 4 more comments
I have a function that returns a promise
like this:
let aFunction= function(){
return new Promise((resolve, reject){
someNodeApi(params, function(err, data)) {
if(err) {
return reject(err);
}
if(data meets certain criteria) {
someOtherNodeApi(params, function(err, data)) {
// handle conditions.
}
}
resolve(data);
}
})
}
I want to have an async
function equivalent for this kind of function. In short, I need something like this:
let aFunction = async function(){
someNodeApi(params, function(err, data){
if(err) {
// reject condition
}
// resolve condition.
})
}
So what should be in above reject
and resolve
conditions so that all the places where I call the function like this:
aFunction()
.then(data=>{})
.catch(err=>{})
It should be unchanged.
EDIT
I have to clarify that my question is not about how to call the async function. But its about how to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called. (A very common scenario when you are dealing with pre async-await era node js code).
javascript node.js promise async-await
3
Your premise is wrong. An async function is called differently (var result = await foo()
). If you want to keep thethen catch
pattern, you need to keep using a Promise. Which brings me to the important question: why do you want to move away from promises?
– Chris G
Nov 23 '18 at 13:31
@ChrisG I want to move away from promises for the same reason as to why async-await was added to node js. Which is that its a better way and more like synchronous programming.
– rahulserver
Nov 23 '18 at 13:34
After your edit, it seems like your question is either. How do I promisify an api, or how do I use async/await. If the first, use a library. If the second, read the docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Matt Way
Nov 23 '18 at 13:56
@MattWay essentially an async function returns a Promise. So using async/await in a certain way becomes a matter of choice and opinion. So I don't think my question is about how do I use it.
– rahulserver
Nov 23 '18 at 14:15
If your question ishow to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called
then as far as I know, the answer is "you can't". Plus, as far as I can gather from your comments, you indeed are asking how to use async / await because if you knew, this question wouldn't exist.essentially an async function returns a Promise
No, it doesn't.
– Chris G
Nov 23 '18 at 14:20
|
show 4 more comments
I have a function that returns a promise
like this:
let aFunction= function(){
return new Promise((resolve, reject){
someNodeApi(params, function(err, data)) {
if(err) {
return reject(err);
}
if(data meets certain criteria) {
someOtherNodeApi(params, function(err, data)) {
// handle conditions.
}
}
resolve(data);
}
})
}
I want to have an async
function equivalent for this kind of function. In short, I need something like this:
let aFunction = async function(){
someNodeApi(params, function(err, data){
if(err) {
// reject condition
}
// resolve condition.
})
}
So what should be in above reject
and resolve
conditions so that all the places where I call the function like this:
aFunction()
.then(data=>{})
.catch(err=>{})
It should be unchanged.
EDIT
I have to clarify that my question is not about how to call the async function. But its about how to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called. (A very common scenario when you are dealing with pre async-await era node js code).
javascript node.js promise async-await
I have a function that returns a promise
like this:
let aFunction= function(){
return new Promise((resolve, reject){
someNodeApi(params, function(err, data)) {
if(err) {
return reject(err);
}
if(data meets certain criteria) {
someOtherNodeApi(params, function(err, data)) {
// handle conditions.
}
}
resolve(data);
}
})
}
I want to have an async
function equivalent for this kind of function. In short, I need something like this:
let aFunction = async function(){
someNodeApi(params, function(err, data){
if(err) {
// reject condition
}
// resolve condition.
})
}
So what should be in above reject
and resolve
conditions so that all the places where I call the function like this:
aFunction()
.then(data=>{})
.catch(err=>{})
It should be unchanged.
EDIT
I have to clarify that my question is not about how to call the async function. But its about how to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called. (A very common scenario when you are dealing with pre async-await era node js code).
javascript node.js promise async-await
javascript node.js promise async-await
edited Nov 23 '18 at 13:52
rahulserver
asked Nov 23 '18 at 13:28
rahulserverrahulserver
3,5701153106
3,5701153106
3
Your premise is wrong. An async function is called differently (var result = await foo()
). If you want to keep thethen catch
pattern, you need to keep using a Promise. Which brings me to the important question: why do you want to move away from promises?
– Chris G
Nov 23 '18 at 13:31
@ChrisG I want to move away from promises for the same reason as to why async-await was added to node js. Which is that its a better way and more like synchronous programming.
– rahulserver
Nov 23 '18 at 13:34
After your edit, it seems like your question is either. How do I promisify an api, or how do I use async/await. If the first, use a library. If the second, read the docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Matt Way
Nov 23 '18 at 13:56
@MattWay essentially an async function returns a Promise. So using async/await in a certain way becomes a matter of choice and opinion. So I don't think my question is about how do I use it.
– rahulserver
Nov 23 '18 at 14:15
If your question ishow to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called
then as far as I know, the answer is "you can't". Plus, as far as I can gather from your comments, you indeed are asking how to use async / await because if you knew, this question wouldn't exist.essentially an async function returns a Promise
No, it doesn't.
– Chris G
Nov 23 '18 at 14:20
|
show 4 more comments
3
Your premise is wrong. An async function is called differently (var result = await foo()
). If you want to keep thethen catch
pattern, you need to keep using a Promise. Which brings me to the important question: why do you want to move away from promises?
– Chris G
Nov 23 '18 at 13:31
@ChrisG I want to move away from promises for the same reason as to why async-await was added to node js. Which is that its a better way and more like synchronous programming.
– rahulserver
Nov 23 '18 at 13:34
After your edit, it seems like your question is either. How do I promisify an api, or how do I use async/await. If the first, use a library. If the second, read the docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Matt Way
Nov 23 '18 at 13:56
@MattWay essentially an async function returns a Promise. So using async/await in a certain way becomes a matter of choice and opinion. So I don't think my question is about how do I use it.
– rahulserver
Nov 23 '18 at 14:15
If your question ishow to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called
then as far as I know, the answer is "you can't". Plus, as far as I can gather from your comments, you indeed are asking how to use async / await because if you knew, this question wouldn't exist.essentially an async function returns a Promise
No, it doesn't.
– Chris G
Nov 23 '18 at 14:20
3
3
Your premise is wrong. An async function is called differently (
var result = await foo()
). If you want to keep the then catch
pattern, you need to keep using a Promise. Which brings me to the important question: why do you want to move away from promises?– Chris G
Nov 23 '18 at 13:31
Your premise is wrong. An async function is called differently (
var result = await foo()
). If you want to keep the then catch
pattern, you need to keep using a Promise. Which brings me to the important question: why do you want to move away from promises?– Chris G
Nov 23 '18 at 13:31
@ChrisG I want to move away from promises for the same reason as to why async-await was added to node js. Which is that its a better way and more like synchronous programming.
– rahulserver
Nov 23 '18 at 13:34
@ChrisG I want to move away from promises for the same reason as to why async-await was added to node js. Which is that its a better way and more like synchronous programming.
– rahulserver
Nov 23 '18 at 13:34
After your edit, it seems like your question is either. How do I promisify an api, or how do I use async/await. If the first, use a library. If the second, read the docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Matt Way
Nov 23 '18 at 13:56
After your edit, it seems like your question is either. How do I promisify an api, or how do I use async/await. If the first, use a library. If the second, read the docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Matt Way
Nov 23 '18 at 13:56
@MattWay essentially an async function returns a Promise. So using async/await in a certain way becomes a matter of choice and opinion. So I don't think my question is about how do I use it.
– rahulserver
Nov 23 '18 at 14:15
@MattWay essentially an async function returns a Promise. So using async/await in a certain way becomes a matter of choice and opinion. So I don't think my question is about how do I use it.
– rahulserver
Nov 23 '18 at 14:15
If your question is
how to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called
then as far as I know, the answer is "you can't". Plus, as far as I can gather from your comments, you indeed are asking how to use async / await because if you knew, this question wouldn't exist. essentially an async function returns a Promise
No, it doesn't.– Chris G
Nov 23 '18 at 14:20
If your question is
how to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called
then as far as I know, the answer is "you can't". Plus, as far as I can gather from your comments, you indeed are asking how to use async / await because if you knew, this question wouldn't exist. essentially an async function returns a Promise
No, it doesn't.– Chris G
Nov 23 '18 at 14:20
|
show 4 more comments
3 Answers
3
active
oldest
votes
This is how I like to write async/await , makes it pretty straightforward. All of the code inside can be read as sync.
EDIT: await will work only if the API returns a promise object that is either resolved or rejected. await does not resolve promises.
function someAPI() {
return new Promise((resolve, reject)=>{
someNodeApi(params, function(err, data){
if(err) {
reject(error)
} else {
resolve(data)
}
// resolve condition.
})
});
}
async function aFunction() {
try {
const result = await someAPI();
return result;
} catch(err){
console.log(err);
}
}
aFunction()
.then((res) => console.log(res))
I think this is a great answer! This does answer my queries. In short we must use await everywhere inside an async function.
– rahulserver
Nov 23 '18 at 13:44
This won't work, as @rahulserver's api is not promisified yet.
– Matt Way
Nov 23 '18 at 13:44
@MattWay you are right. But I can use utils.promisify to do that conversion. Conceptually this answer addresses my query. However it would be worth editing the answer to include that the function needs to be promisified
– rahulserver
Nov 23 '18 at 13:45
@rahulserver If you use a promisifying library, then this answer is totally redundant. As I said in my answer, you don't need aFunction at all.
– Matt Way
Nov 23 '18 at 13:46
Yes, your API needs to return a promise, I will edit to show you.
– squeekyDave
Nov 23 '18 at 13:46
|
show 1 more comment
When changing to async/await, what changes isn't your promise setup, but rather how you make calls to your promises. For example:
aFunction()
.then(data=>{})
.catch(err=>{})
// becomes
try{
const data = await aFunction()
}catch(err){
// do something with err
}
Just bear in mind that the function that uses await needs to be set to async
.
If your someNodeApi
call was already setup for promises, then the result would still be exactly the same, you simply wouldn't need aFunction
at all. For example, if you used a promisifying library on your api, then you don't need aFunction
at all.
someNodeApi(params)
.then(data => {})
.catch(err => {})
// or
const data = await someNodeApi(params)
if(data meets certain criteria) {
const otherData = someOtherNodeApi(params)
}
Thanks @Matt. Certainly looks good. But then what would you do in cases when you are going to use a lot of api calls(callback based) inside that async function? I mean i just want to make the code inside the function more like synchronous. In short If node syntax allowed it, i would just use await keyword inside my promise based functions without async.
– rahulserver
Nov 23 '18 at 13:40
add a comment |
Snippet1 : Here, you can see the usage of async-await
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
(async () => {
try {
let result1 = await fn(20);
console.log(result1);
let result2 = await fn(5);
console.log(result2);
}
catch(err) {
console.error(err);
}
})();
Snippet2 : Here you can see that using .then.catch will not harm or break any of your code.
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
fn(20).then(response => {
console.log(response);
});
fn(5)
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
})
It does not break your code if you use fn().then.catch pattern on a Promise returning async fumction.
However, using await makes it more elegant.
Feel free to refer a detailed article that I have written on basics of
async-await and why async-await compared to .then.catch pattern, pros
and cons here: https://github.com/cskru/asyncAwaitSimplified
I have included code snippets which you can directly copy paste and try out.
PS: I have used async IIFE in the above snippets.
This is because awaits can be made inside async function/context only.
I'd also recommend you to check this article to get a solid foundation wrt async-await.
Happy learning!
Cheers,
Kruthika
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447608%2fasync-function-equivalent-of-a-promise%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
This is how I like to write async/await , makes it pretty straightforward. All of the code inside can be read as sync.
EDIT: await will work only if the API returns a promise object that is either resolved or rejected. await does not resolve promises.
function someAPI() {
return new Promise((resolve, reject)=>{
someNodeApi(params, function(err, data){
if(err) {
reject(error)
} else {
resolve(data)
}
// resolve condition.
})
});
}
async function aFunction() {
try {
const result = await someAPI();
return result;
} catch(err){
console.log(err);
}
}
aFunction()
.then((res) => console.log(res))
I think this is a great answer! This does answer my queries. In short we must use await everywhere inside an async function.
– rahulserver
Nov 23 '18 at 13:44
This won't work, as @rahulserver's api is not promisified yet.
– Matt Way
Nov 23 '18 at 13:44
@MattWay you are right. But I can use utils.promisify to do that conversion. Conceptually this answer addresses my query. However it would be worth editing the answer to include that the function needs to be promisified
– rahulserver
Nov 23 '18 at 13:45
@rahulserver If you use a promisifying library, then this answer is totally redundant. As I said in my answer, you don't need aFunction at all.
– Matt Way
Nov 23 '18 at 13:46
Yes, your API needs to return a promise, I will edit to show you.
– squeekyDave
Nov 23 '18 at 13:46
|
show 1 more comment
This is how I like to write async/await , makes it pretty straightforward. All of the code inside can be read as sync.
EDIT: await will work only if the API returns a promise object that is either resolved or rejected. await does not resolve promises.
function someAPI() {
return new Promise((resolve, reject)=>{
someNodeApi(params, function(err, data){
if(err) {
reject(error)
} else {
resolve(data)
}
// resolve condition.
})
});
}
async function aFunction() {
try {
const result = await someAPI();
return result;
} catch(err){
console.log(err);
}
}
aFunction()
.then((res) => console.log(res))
I think this is a great answer! This does answer my queries. In short we must use await everywhere inside an async function.
– rahulserver
Nov 23 '18 at 13:44
This won't work, as @rahulserver's api is not promisified yet.
– Matt Way
Nov 23 '18 at 13:44
@MattWay you are right. But I can use utils.promisify to do that conversion. Conceptually this answer addresses my query. However it would be worth editing the answer to include that the function needs to be promisified
– rahulserver
Nov 23 '18 at 13:45
@rahulserver If you use a promisifying library, then this answer is totally redundant. As I said in my answer, you don't need aFunction at all.
– Matt Way
Nov 23 '18 at 13:46
Yes, your API needs to return a promise, I will edit to show you.
– squeekyDave
Nov 23 '18 at 13:46
|
show 1 more comment
This is how I like to write async/await , makes it pretty straightforward. All of the code inside can be read as sync.
EDIT: await will work only if the API returns a promise object that is either resolved or rejected. await does not resolve promises.
function someAPI() {
return new Promise((resolve, reject)=>{
someNodeApi(params, function(err, data){
if(err) {
reject(error)
} else {
resolve(data)
}
// resolve condition.
})
});
}
async function aFunction() {
try {
const result = await someAPI();
return result;
} catch(err){
console.log(err);
}
}
aFunction()
.then((res) => console.log(res))
This is how I like to write async/await , makes it pretty straightforward. All of the code inside can be read as sync.
EDIT: await will work only if the API returns a promise object that is either resolved or rejected. await does not resolve promises.
function someAPI() {
return new Promise((resolve, reject)=>{
someNodeApi(params, function(err, data){
if(err) {
reject(error)
} else {
resolve(data)
}
// resolve condition.
})
});
}
async function aFunction() {
try {
const result = await someAPI();
return result;
} catch(err){
console.log(err);
}
}
aFunction()
.then((res) => console.log(res))
edited Nov 23 '18 at 13:49
answered Nov 23 '18 at 13:41
squeekyDavesqueekyDave
489217
489217
I think this is a great answer! This does answer my queries. In short we must use await everywhere inside an async function.
– rahulserver
Nov 23 '18 at 13:44
This won't work, as @rahulserver's api is not promisified yet.
– Matt Way
Nov 23 '18 at 13:44
@MattWay you are right. But I can use utils.promisify to do that conversion. Conceptually this answer addresses my query. However it would be worth editing the answer to include that the function needs to be promisified
– rahulserver
Nov 23 '18 at 13:45
@rahulserver If you use a promisifying library, then this answer is totally redundant. As I said in my answer, you don't need aFunction at all.
– Matt Way
Nov 23 '18 at 13:46
Yes, your API needs to return a promise, I will edit to show you.
– squeekyDave
Nov 23 '18 at 13:46
|
show 1 more comment
I think this is a great answer! This does answer my queries. In short we must use await everywhere inside an async function.
– rahulserver
Nov 23 '18 at 13:44
This won't work, as @rahulserver's api is not promisified yet.
– Matt Way
Nov 23 '18 at 13:44
@MattWay you are right. But I can use utils.promisify to do that conversion. Conceptually this answer addresses my query. However it would be worth editing the answer to include that the function needs to be promisified
– rahulserver
Nov 23 '18 at 13:45
@rahulserver If you use a promisifying library, then this answer is totally redundant. As I said in my answer, you don't need aFunction at all.
– Matt Way
Nov 23 '18 at 13:46
Yes, your API needs to return a promise, I will edit to show you.
– squeekyDave
Nov 23 '18 at 13:46
I think this is a great answer! This does answer my queries. In short we must use await everywhere inside an async function.
– rahulserver
Nov 23 '18 at 13:44
I think this is a great answer! This does answer my queries. In short we must use await everywhere inside an async function.
– rahulserver
Nov 23 '18 at 13:44
This won't work, as @rahulserver's api is not promisified yet.
– Matt Way
Nov 23 '18 at 13:44
This won't work, as @rahulserver's api is not promisified yet.
– Matt Way
Nov 23 '18 at 13:44
@MattWay you are right. But I can use utils.promisify to do that conversion. Conceptually this answer addresses my query. However it would be worth editing the answer to include that the function needs to be promisified
– rahulserver
Nov 23 '18 at 13:45
@MattWay you are right. But I can use utils.promisify to do that conversion. Conceptually this answer addresses my query. However it would be worth editing the answer to include that the function needs to be promisified
– rahulserver
Nov 23 '18 at 13:45
@rahulserver If you use a promisifying library, then this answer is totally redundant. As I said in my answer, you don't need aFunction at all.
– Matt Way
Nov 23 '18 at 13:46
@rahulserver If you use a promisifying library, then this answer is totally redundant. As I said in my answer, you don't need aFunction at all.
– Matt Way
Nov 23 '18 at 13:46
Yes, your API needs to return a promise, I will edit to show you.
– squeekyDave
Nov 23 '18 at 13:46
Yes, your API needs to return a promise, I will edit to show you.
– squeekyDave
Nov 23 '18 at 13:46
|
show 1 more comment
When changing to async/await, what changes isn't your promise setup, but rather how you make calls to your promises. For example:
aFunction()
.then(data=>{})
.catch(err=>{})
// becomes
try{
const data = await aFunction()
}catch(err){
// do something with err
}
Just bear in mind that the function that uses await needs to be set to async
.
If your someNodeApi
call was already setup for promises, then the result would still be exactly the same, you simply wouldn't need aFunction
at all. For example, if you used a promisifying library on your api, then you don't need aFunction
at all.
someNodeApi(params)
.then(data => {})
.catch(err => {})
// or
const data = await someNodeApi(params)
if(data meets certain criteria) {
const otherData = someOtherNodeApi(params)
}
Thanks @Matt. Certainly looks good. But then what would you do in cases when you are going to use a lot of api calls(callback based) inside that async function? I mean i just want to make the code inside the function more like synchronous. In short If node syntax allowed it, i would just use await keyword inside my promise based functions without async.
– rahulserver
Nov 23 '18 at 13:40
add a comment |
When changing to async/await, what changes isn't your promise setup, but rather how you make calls to your promises. For example:
aFunction()
.then(data=>{})
.catch(err=>{})
// becomes
try{
const data = await aFunction()
}catch(err){
// do something with err
}
Just bear in mind that the function that uses await needs to be set to async
.
If your someNodeApi
call was already setup for promises, then the result would still be exactly the same, you simply wouldn't need aFunction
at all. For example, if you used a promisifying library on your api, then you don't need aFunction
at all.
someNodeApi(params)
.then(data => {})
.catch(err => {})
// or
const data = await someNodeApi(params)
if(data meets certain criteria) {
const otherData = someOtherNodeApi(params)
}
Thanks @Matt. Certainly looks good. But then what would you do in cases when you are going to use a lot of api calls(callback based) inside that async function? I mean i just want to make the code inside the function more like synchronous. In short If node syntax allowed it, i would just use await keyword inside my promise based functions without async.
– rahulserver
Nov 23 '18 at 13:40
add a comment |
When changing to async/await, what changes isn't your promise setup, but rather how you make calls to your promises. For example:
aFunction()
.then(data=>{})
.catch(err=>{})
// becomes
try{
const data = await aFunction()
}catch(err){
// do something with err
}
Just bear in mind that the function that uses await needs to be set to async
.
If your someNodeApi
call was already setup for promises, then the result would still be exactly the same, you simply wouldn't need aFunction
at all. For example, if you used a promisifying library on your api, then you don't need aFunction
at all.
someNodeApi(params)
.then(data => {})
.catch(err => {})
// or
const data = await someNodeApi(params)
if(data meets certain criteria) {
const otherData = someOtherNodeApi(params)
}
When changing to async/await, what changes isn't your promise setup, but rather how you make calls to your promises. For example:
aFunction()
.then(data=>{})
.catch(err=>{})
// becomes
try{
const data = await aFunction()
}catch(err){
// do something with err
}
Just bear in mind that the function that uses await needs to be set to async
.
If your someNodeApi
call was already setup for promises, then the result would still be exactly the same, you simply wouldn't need aFunction
at all. For example, if you used a promisifying library on your api, then you don't need aFunction
at all.
someNodeApi(params)
.then(data => {})
.catch(err => {})
// or
const data = await someNodeApi(params)
if(data meets certain criteria) {
const otherData = someOtherNodeApi(params)
}
edited Nov 23 '18 at 13:55
answered Nov 23 '18 at 13:37
Matt WayMatt Way
23.4k96069
23.4k96069
Thanks @Matt. Certainly looks good. But then what would you do in cases when you are going to use a lot of api calls(callback based) inside that async function? I mean i just want to make the code inside the function more like synchronous. In short If node syntax allowed it, i would just use await keyword inside my promise based functions without async.
– rahulserver
Nov 23 '18 at 13:40
add a comment |
Thanks @Matt. Certainly looks good. But then what would you do in cases when you are going to use a lot of api calls(callback based) inside that async function? I mean i just want to make the code inside the function more like synchronous. In short If node syntax allowed it, i would just use await keyword inside my promise based functions without async.
– rahulserver
Nov 23 '18 at 13:40
Thanks @Matt. Certainly looks good. But then what would you do in cases when you are going to use a lot of api calls(callback based) inside that async function? I mean i just want to make the code inside the function more like synchronous. In short If node syntax allowed it, i would just use await keyword inside my promise based functions without async.
– rahulserver
Nov 23 '18 at 13:40
Thanks @Matt. Certainly looks good. But then what would you do in cases when you are going to use a lot of api calls(callback based) inside that async function? I mean i just want to make the code inside the function more like synchronous. In short If node syntax allowed it, i would just use await keyword inside my promise based functions without async.
– rahulserver
Nov 23 '18 at 13:40
add a comment |
Snippet1 : Here, you can see the usage of async-await
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
(async () => {
try {
let result1 = await fn(20);
console.log(result1);
let result2 = await fn(5);
console.log(result2);
}
catch(err) {
console.error(err);
}
})();
Snippet2 : Here you can see that using .then.catch will not harm or break any of your code.
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
fn(20).then(response => {
console.log(response);
});
fn(5)
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
})
It does not break your code if you use fn().then.catch pattern on a Promise returning async fumction.
However, using await makes it more elegant.
Feel free to refer a detailed article that I have written on basics of
async-await and why async-await compared to .then.catch pattern, pros
and cons here: https://github.com/cskru/asyncAwaitSimplified
I have included code snippets which you can directly copy paste and try out.
PS: I have used async IIFE in the above snippets.
This is because awaits can be made inside async function/context only.
I'd also recommend you to check this article to get a solid foundation wrt async-await.
Happy learning!
Cheers,
Kruthika
add a comment |
Snippet1 : Here, you can see the usage of async-await
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
(async () => {
try {
let result1 = await fn(20);
console.log(result1);
let result2 = await fn(5);
console.log(result2);
}
catch(err) {
console.error(err);
}
})();
Snippet2 : Here you can see that using .then.catch will not harm or break any of your code.
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
fn(20).then(response => {
console.log(response);
});
fn(5)
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
})
It does not break your code if you use fn().then.catch pattern on a Promise returning async fumction.
However, using await makes it more elegant.
Feel free to refer a detailed article that I have written on basics of
async-await and why async-await compared to .then.catch pattern, pros
and cons here: https://github.com/cskru/asyncAwaitSimplified
I have included code snippets which you can directly copy paste and try out.
PS: I have used async IIFE in the above snippets.
This is because awaits can be made inside async function/context only.
I'd also recommend you to check this article to get a solid foundation wrt async-await.
Happy learning!
Cheers,
Kruthika
add a comment |
Snippet1 : Here, you can see the usage of async-await
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
(async () => {
try {
let result1 = await fn(20);
console.log(result1);
let result2 = await fn(5);
console.log(result2);
}
catch(err) {
console.error(err);
}
})();
Snippet2 : Here you can see that using .then.catch will not harm or break any of your code.
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
fn(20).then(response => {
console.log(response);
});
fn(5)
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
})
It does not break your code if you use fn().then.catch pattern on a Promise returning async fumction.
However, using await makes it more elegant.
Feel free to refer a detailed article that I have written on basics of
async-await and why async-await compared to .then.catch pattern, pros
and cons here: https://github.com/cskru/asyncAwaitSimplified
I have included code snippets which you can directly copy paste and try out.
PS: I have used async IIFE in the above snippets.
This is because awaits can be made inside async function/context only.
I'd also recommend you to check this article to get a solid foundation wrt async-await.
Happy learning!
Cheers,
Kruthika
Snippet1 : Here, you can see the usage of async-await
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
(async () => {
try {
let result1 = await fn(20);
console.log(result1);
let result2 = await fn(5);
console.log(result2);
}
catch(err) {
console.error(err);
}
})();
Snippet2 : Here you can see that using .then.catch will not harm or break any of your code.
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
fn(20).then(response => {
console.log(response);
});
fn(5)
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
})
It does not break your code if you use fn().then.catch pattern on a Promise returning async fumction.
However, using await makes it more elegant.
Feel free to refer a detailed article that I have written on basics of
async-await and why async-await compared to .then.catch pattern, pros
and cons here: https://github.com/cskru/asyncAwaitSimplified
I have included code snippets which you can directly copy paste and try out.
PS: I have used async IIFE in the above snippets.
This is because awaits can be made inside async function/context only.
I'd also recommend you to check this article to get a solid foundation wrt async-await.
Happy learning!
Cheers,
Kruthika
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
(async () => {
try {
let result1 = await fn(20);
console.log(result1);
let result2 = await fn(5);
console.log(result2);
}
catch(err) {
console.error(err);
}
})();
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
(async () => {
try {
let result1 = await fn(20);
console.log(result1);
let result2 = await fn(5);
console.log(result2);
}
catch(err) {
console.error(err);
}
})();
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
fn(20).then(response => {
console.log(response);
});
fn(5)
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
})
let fn = async function(a) {
let val = 10;
return new Promise((resolve, reject) => {
if(a > val) {
resolve("+++++Resolved");
}
else {
reject("++++++Rejected")
}
})
};
fn(20).then(response => {
console.log(response);
});
fn(5)
.then(response => {
console.log(response);
})
.catch(err => {
console.error(err);
})
edited Nov 26 '18 at 16:25
answered Nov 23 '18 at 14:09
Kruthika C SKruthika C S
338214
338214
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447608%2fasync-function-equivalent-of-a-promise%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
Your premise is wrong. An async function is called differently (
var result = await foo()
). If you want to keep thethen catch
pattern, you need to keep using a Promise. Which brings me to the important question: why do you want to move away from promises?– Chris G
Nov 23 '18 at 13:31
@ChrisG I want to move away from promises for the same reason as to why async-await was added to node js. Which is that its a better way and more like synchronous programming.
– rahulserver
Nov 23 '18 at 13:34
After your edit, it seems like your question is either. How do I promisify an api, or how do I use async/await. If the first, use a library. If the second, read the docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Matt Way
Nov 23 '18 at 13:56
@MattWay essentially an async function returns a Promise. So using async/await in a certain way becomes a matter of choice and opinion. So I don't think my question is about how do I use it.
– rahulserver
Nov 23 '18 at 14:15
If your question is
how to convert a function that returns a Promise to be able to use the goodness of async-await pattern without having to modify the way its called
then as far as I know, the answer is "you can't". Plus, as far as I can gather from your comments, you indeed are asking how to use async / await because if you knew, this question wouldn't exist.essentially an async function returns a Promise
No, it doesn't.– Chris G
Nov 23 '18 at 14:20