Unable to retrieve data from a promise - javascript

I am unable to retrieve data from a promise using then(). Where am I going wrong?
async function A(){
await new Promise((resolve, reject) => setTimeout(()=>{},1000));
return 45;
}
A().then(data => console.log(data))
I'm running this code with nodejs.
I expect the output to print 45. But the program just executes for 1 second and doesn't print anything.
If I remove the timeout statement, I am able to print 45.
Where am I going wrong?

You need to resolve your promise and then return can run.
async function A() {
await new Promise((resolve, reject) => setTimeout(() => resolve(), 1000));
return 45;
}
A().then(data => console.log(data))
You could also return promise from A function and then use async/await.
function A() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(45), 1000)
})
}
(async() => {
const res = await A();
console.log(res)
})()

Your function A should return a promise.
function A() {
return new Promise((resolve, reject) => setTimeout(() => resolve('hello'), 1000));
}
A().then(data => console.log(data))

Function A should return a promise and use async/await along with IFI (Immediate Function Invocation method)
function A(){
return new Promise((resolve, reject) => setTimeout(()=>{resolve(100)},1000));
}
(async () => {
var data = await A()
console.log(data)
})();

Related

Why is this output reached?

Can anyone tell me why this code outputs the following? I am completely lost on async functions and close to just giving up.
The first await does what I expect and waits 1 second before executing. However, somehow 301 is outputted before the then before it is executed which seems to completely defy the literal definition of then. Done is outputted then somehow it goes back and executes the second then statement.
async function test() {
const promise1 = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
console.log('First await executed')
}, 1000)
}).then(() => {
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
console.log("This was executed")
}, 1000)
})
}).then(() => Promise.resolve(301));
console.log(promise1)
await setTimeout(() => console.log(1000), 1000)
console.log("Done");
}
test()

Issues with async/await

I'm trying to use async/await for a very basic promise, but I'm getting the error: SyntaxError: await is only valid in async function. However, I believe I'm using await for an async function.
function getNumber(mult) {
return new Promise((resolve, reject) => {
resolve(10);
}).then((val) => {
return new Promise((resolve, reject) => {
resolve(val * mult)
//reject("Error");
}).then((val2) => val2);
}).catch((err) => {
return err;
})
}
const calculate = async (x) => await Promise.resolve(getNumber(x))
const val = await calculate(2)
You cannot have the initial function with an await at the top level... just a modification.
function getNumber(mult) {
return new Promise((resolve, reject) => {
resolve(10);
}).then((val) => {
return new Promise((resolve, reject) => {
resolve(val * mult)
//reject("Error");
}).then((val2) => val2);
}).catch((err) => {
return err;
})
}
const calculate = (x) => Promise.resolve(getNumber(x));
const val = calculate(2).then(resp => {
console.log('do something with response: ', resp)
})
To only focus on why you're getting that error, the await in await calculate(2) isn't in an asynchronous function. If you can make it asynchronous function then do that but if not then you can use the .then() function like below:
calculate(2).then(val => {
//Your code here
}

How to correctly resolve a promise within promise constructor

const setTimeoutProm = (delay) => new Promise(res => setTimeout(() => res(delay),delay))
I want to do something like,
const asyncOpr = (delay) => {
return new Promise((resolve, reject) => {
//update delay for some reason.
const updatedDelay = delay * 2;
setTimeoutProm(updatedDelay).then(res => {
resolve(res);
}).catch(err => {})
})
}
asyncOpr(2000).then(() => alert("resolved")) //this works
This works as expected, but I am not sure if this is correct way of doing this or is there any better way of doing this ?
No, actually the way you do it is an antipattern.
You can just return a promise from the function:
const asyncOpr = (delay) => {
return setTimeoutProm(delay);
};
If needed, a Promise could also be returned from inside a .then:
doA()
.then(() => setTineoutProm(1000))
.then(() => doB());
Or it can also be awaited inside an async function:
async function asyncOpr(delay) {
//...
await setTimeoutProm(delay);
//...
}

Promise - `then()` not works as expect

I do have 2 function. I am chaining with then() method for promise. But I am trying to initiate the second function after the first promise happend. But now the second function call as first. how to fix this?
or any issue with my code?
here is my try:
var getData = function(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(42); //consoles as second
}, 5000);
})
}
var getDataMoreData = function(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(43); //consoles as first
}, 3000);
})
}
getData().then((data)=> console.log('Data', data)).then(getDataMoreData().then((data)=> console.log('data--', data )));
Live Demo
.then accepts a function as a parameter. When you do
.then(getDataMoreData()
.then((data) => console.log('data--', data))
);
, it immediately calls getDataMoreData() (with the expectation that it will return a function that it can put into the promise chain). But getDataMoreData does not return a function - it returns a promise.
Any function calls immediately within a then get executed immediately, as it attempts to build the .then promise chain. Simply list the function variable inside the then instead of calling it:
var getData = function() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(42);
}, 500);
})
}
var getDataMoreData = function() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(43);
}, 300);
})
}
getData()
.then((data) => console.log('Data', data))
.then(getDataMoreData)
.then((data) => console.log('data--', data));

JavaScript Promise wrapped in function or bare?

If I'm calling a function that is a promise, do I need to do this "wrap it in another function" layer?
Promise
.resolve()
.then(()=>{ // this part seems excessive
return new Promise(resolve={
// my function's guts
Can I return the new promise directly, like
Promise
.resolve()
.then(new Promise(resolve={
// my function's guts
If I'm calling a function that is a promise, do I need to do this
"wrap it in another function" layer?
Yes otherwise it'll be executed immediately I recommend you create your promises within a named function that way it allows you to keep your chain neat and readable and code more reusable.
myTask1()
.then(myTask2)
.then(myTask3);
function myTask1() {
return new Promise((resolve, reject) => {
console.log("Task 1");
resolve("Task 1");
})
}
function myTask2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Task 2");
resolve("Task 2");
}, 1000)
})
}
function myTask3() {
return new Promise((resolve, reject) => {
console.log("Task 3");
resolve("Task 3");
})
}
Can I return the new promise directly, like.... .then(new Promise(resolve={?
No there's one critical difference with instantiating the promise like that. When you wrap the promise in a function it isn't evaluated until the previous promise completes whereas if you instantiate it inline then it's evaluated immediately which may cause unexpected results:
new Promise((resolve, reject) => {
resolve()
})
.then(new Promise((resolve, reject) => {
console.log("Task 1");
}))
.then(new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Task 2");
resolve("Task 2");
}, 1000);
}))
.then(new Promise((resolve, reject) => {
console.log("Task 3");
resolve("Task 3");
}))
To make the above work you could change it so that the closure returns a promise, but it starts to look pretty messy:
new Promise((resolve, reject) => {
resolve()
})
.then(() => {
return new Promise((resolve, reject) => {
console.log("Task 1");
resolve("Task 1");
})
})
.then(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Task 2");
resolve("Task 2");
}, 1000);
});
})
.then(() => {
return new Promise((resolve, reject) => {
console.log("Task 3");
resolve("Task 3");
});
})
You do have to wrap the promise in another function.
However, you can shorten it a bit because:
() => {
return new Promise()
}
is the same as
() => new Promise()
So you could do something like this:
Promise
.resolve()
.then(() => new Promise(resolve => {
// your function's guts
There is no need to use Promise.resolve() when creating a new promise.
The usual way to create a promise is to make a function that returns the promise:
function myFunc() {
return new Promise((resolve, reject) => {
// your async logic here
});
}
Then, you call it like this:
myFunc().then(result => {
// code that uses async result here
});
And, you have put your promise creation logic into a reusable function.
It is possible (though usually less practical) to create a new promise without putting it in a containing function. For example, you can do this:
new Promise((resolve, reject) => {
// async logic here that eventually calls resolve or reject
}).then(result => {
// process async result here
}).catch(err => {
// process error here
});
The handler for then could simply return a value.
Promise.resolve('value').then(() => 'otherValue');

Categories

Resources