I'm trying to get the value of an inputed variable on a callback function and assign it into another variable value outside this callback function.
I'm using async/await but not working (the assignment runs before the callback function), any suggestion?
async function iniciar() {
let my_prep = '';
await readline.question('Insert preposition', (prep) => {
**my_prep = prep;**
readline.close();
});
console.log('OK',my_prep);
return true;
}
Thanks for reading!
You can do something like this.
const question = () => {
return new Promise((resolve, reject) => {
readline.question('Insert preposition ', (prep) => {
readline.close();
resolve(prep)
})
})
}
async function iniciar() {
let my_prep = await question();
console.log('OK',my_prep);
return true;
}
await keyword waits on the promise to resolve, so you need to return promise. Also the use of async/await and promises is to avoid callback hell.
Related
I just learnt "async" that "async" ensures that the function returns promise then i tried to make a promise with writing "async" instead of writing "new Promise" and it didn't work out so i want to know is it wrong syntax or it will never work out and i will have to write only new promise?
// This is a code
async function gets(){
let gets1 = async()=>{
return 45;
}
gets1.then((value)=>{
console.log(value, "inside gets1")
})
}
gets()
As already pointed out, you need to call a function fn().then(, not just reference it fn.then(.
Also if you don't use the await, you also don't need the wrapping await
const gets = () => {
const gets1 = async() => {
return 45;
}
gets1().then((value) => {
console.log(value, "inside gets1")
})
};
gets();
Or use async with await to get rid of Promise.then():
const gets = async () => {
const gets1 = async() => {
return 45;
};
const value = await gets1();
console.log(value, "inside gets1")
};
gets();
Make sure to read top to bottom: async Function
You forgot to call the function
It should be gets1().then() and not gets1.then()
async function gets(){
let gets1 = async()=>{
return 45;
}
gets1().then((value)=>{
console.log(value, "inside gets1")
})
}
gets()
The whole thing will work without the outer async function too:
let gets1 = async()=>"msg from gets1";
gets1().then(console.log)
I'm trying to return value of pagenumber from inner function to another. But due to asynchronous nature of javascript. I'm unable to do it as outer function gets executed earlier as compared to inner one. I'm trying to use callback to it but it will produce error if i call outer function(from somewhere else) without callback. My code is,
'GrabNewResponse':function(credentials,width){
let pagenumber=0;
app.request.get(url,function(data){
let result=JSON.parse(data);
pagenumber=result.data.pagenumber;
if(result.success===true){
app.dialog.close();
}
});
return pagenumber;
},
Asynchronous operations in Javascript cannot be effectively handled without callbacks, promises or the async/await keywords.
const request = () => new Promise((resolve, reject) =>
app.request.get(url, (response) => response.success
? resolve(response)
: reject(response)))
const o = {
async GrabNewResponse(credentials, width) {
const response = JSON.parse(await request(url))
const { data: { pagenumber = 0 } } = response
app.dialog.close()
return pagenumber
}
}
How to change the value of data inside the asyncCall() and set it to the resolve value of the promise which is b.
What I wanted is that the asyncCall() will return b.
But what happen is that asyncCall() returns a Promise object.
function resolveAfter2Seconds(data) {
return new Promise(resolve => {
resolve(data);
});
}
async function asyncCall() {
let data = "a";
var result = await resolveAfter2Seconds("b");
data = result;
return data;
}
asyncCall();
Use IIFE
Making the function async will automatically have it return a Promise. You will either have to await it, or use .then to access the resolved value. IIFE stands for "Immediately Invoked Function Expression" – Tim VN
function resolveAfter2Seconds(data) {
return new Promise(resolve => {
resolve(data);
});
}
async function asyncCall() {
let data = "a";
var result = await resolveAfter2Seconds("b");
data = result;
return data;
}
(async function() {
console.log(await asyncCall())
})()
An async function will always return a Promise (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Return_value).
If you put a console.log(result) statement in the asyncCall() function body, you will realize that the value is actually resolved right there and can be used as you'd expect it. But as documented, the return value of an async function will always be "promisified", so you'd have to "await" that function call too.
To do that at the top (global) level, you can either use an IIFE (Immediately Invoked Function Expression):
(async () => console.log(await asyncCall()))();
or fall back to classical callback functions using Promise.then():
asyncCall().then(value => console.log(value));
Some browsers also support top level await expressions:
await asyncCall();
declaring function with async will return classic Promise.
so you have to use callbacks or await.
async function asyncCall() will return Promise not the result you want to.
asyncCall().then((data) => console.log('in data is your result'));
Async functions return a promise itself:
function resolveAfter2Seconds(data) {
return new Promise(resolve => {
return resolve(data);
});
}
async function asyncCall() {
const result = await resolveAfter2Seconds("b");
return result;
}
asyncCall().then(
data => console.log(data)
);
Can someone help me understand why the following code prints blank? I'm expecting it to print "done" as I assume that the await will make the program wait for the promise to resolve.
Thanks for the help!
var y = '';
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 1000)
});
let result = await promise; // wait till the promise resolves (*)
y = result;
}
f().then(console.log(y));
You must pass a callback function to then, not call console.log immediately and pass its return value:
f().then(() => console.log(y));
Of course the code would be much better if you didn't use a global variable but rather returned the value from the async function so that the promise fulfilled with it:
async function f() {
const promise = new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
});
await promise;
const result = "done!";
return result;
}
f().then((y) => console.log(y));
I have got a javascript code like this:
function justTesting() {
promise.then(function(output) {
return output + 1;
});
}
var test = justTesting();
I have got always an undefined value for the var test. I think that it is because the promises are not resolved yet..there is a way to return a value from a promise?
When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails).
Source: https://web.dev/promises/#queuing-asynchronous-actions
To use a promise, you have to either call a function that creates a promise or you have to create one yourself. You don't really describe what problem you're really trying to solve, but here's how you would create a promise yourself:
function justTesting(input) {
return new Promise(function(resolve, reject) {
// some async operation here
setTimeout(function() {
// resolve the promise with some value
resolve(input + 10);
}, 500);
});
}
justTesting(29).then(function(val) {
// you access the value from the promise here
log(val);
});
// display output in snippet
function log(x) {
document.write(x);
}
Or, if you already have a function that returns a promise, you can use that function and return its promise:
// function that returns a promise
function delay(t) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, t);
});
}
function justTesting(input) {
return delay(100).then(function() {
return input + 10;
});
}
justTesting(29).then(function(val) {
// you access the value from the promise here
log(val);
});
// display output in snippet
function log(x) {
document.write(x);
}
What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.
// new answer
function justTesting() {
return new Promise((resolve, reject) => {
if (true) {
return resolve("testing");
} else {
return reject("promise failed");
}
});
}
justTesting()
.then(res => {
let test = res;
// do something with the output :)
})
.catch(err => {
console.log(err);
});
Hope this helps!
// old answer
function justTesting() {
return promise.then(function(output) {
return output + 1;
});
}
justTesting().then((res) => {
var test = res;
// do something with the output :)
}
I prefer to use "await" command and async functions to get rid of confusions of promises,
In this case I would write an asynchronous function first,
this will be used instead of the anonymous function called under "promise.then" part of this question :
async function SubFunction(output){
// Call to database , returns a promise, like an Ajax call etc :
const response = await axios.get( GetApiHost() + '/api/some_endpoint')
// Return :
return response;
}
and then I would call this function from main function :
async function justTesting() {
const lv_result = await SubFunction(output);
return lv_result + 1;
}
Noting that I returned both main function and sub function to async functions here.
Promises don't "return" values, they pass them to a callback (which you supply with .then()).
It's probably trying to say that you're supposed to do resolve(someObject); inside the promise implementation.
Then in your then code you can reference someObject to do what you want.
I think what the original poster wants is to return an unwrapped value from a promise without actually returning another promise. Unless proven otherwise, I'm afraid this is not possible outside of a then() or async/await context. You always get a promise no matter what.
You need to make use of reference data type like array or object.
function foo(u,n){
let result = [];
const userBrands = new Promise((res, rej)=> {
res(['brand 1', 'brand 3']);
})
userBrands.then((ub)=>{
return new Promise((res, rej) =>{
res([...ub, 'brand 4', 'brand 5']);
})
}).then(response => {
return result.push(...response);
});
return result;
};
foo();
You cannot return value after resolving promise. Instead call another function when promise is resolved:
function justTesting() {
promise.then(function(output) {
// instead of return call another function
afterResolve(output + 1);
});
}
function afterResolve(result) {
// do something with result
}
var test = justTesting();