This question already has answers here:
async/await implicitly returns promise?
(5 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
Async function returning promise, instead of value
(3 answers)
How can I access the value of a promise?
(14 answers)
What are asynchronous functions in JavaScript? What is "async" and "await" in JavaScript?
(2 answers)
Closed 21 days ago.
funcA recieves an array and returns sum using a Promise
funcB calls funcA and doubles that sum
when trying to console log the result from funcB (the sum * 2) it doesn't work
here is my code:
let arr1 = [[1,6,3,9],[6,12,5,21],[4,11,23,1]]
async function funcA(arr) {
let sum = await new Promise((resolve) => {
setTimeout(() => {
let innerSum = 0
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr[i].length; j++) {
innerSum += arr[i][j]
}
}
resolve(innerSum) }, 2000)
})
return sum
}
async function funcB(prom) {
let data1 = await prom.then(data => {
return data * 2
})
return data1
}
console.log(funcB (funcA(arr1)).then(data => {
return data
}) )
the output is:
Promise { }
what am I missing?
thanks.
Related
This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Calling functions with setTimeout()
(6 answers)
Combination of async function + await + setTimeout
(17 answers)
Closed 7 months ago.
I have a program which is supposed to demonstrate a bubble sort, however I want the program to wait one second after every swap to demonstrate what swap is being made. Attached is my code:
function bubbleSort(arr){
for(var i = 0; i < arr.length-1; i++){
for(var j = 0; j < arr.length-i-1; j++){
if(arr[j] > arr[j+1]){
swap(arr,j,j+1);
}
}
}
}
Here is my swap function:
async function swap (arr,a,b){
var temp = arr[a];
var temp2 = arr;
temp2[a] = arr[b];
temp2[b] = temp;
await setTimeout(updateText(),1000);
return temp2;
}
And here is updateText:
function updateText(arrayText){
document.getElementById('arrayText').innerHTML = printArray(arr);
}
Whenever I execute the bubbleSort() function, my array goes from unsorted to sorted instantly, and does not show the swaps needed to reach the solved array.
updateText() is not called anywhere else in my program except for in the swap function.
Any help would be greatly appreciated and I can provide clarifications if needed.
The issue is the setTimeout function does not return a promise, which await expects.
function resolveAfter1Second() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 1000);
});
}
async function swap (arr,a,b){
var temp = arr[a];
var temp2 = arr;
temp2[a] = arr[b];
temp2[b] = temp;
await resolveAfter1Second();
return temp2;
}
Here's an example that simply logs the array to the console. You can replace the console.log(arr) line with a web page update, as needed.
const waitFor = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
async function bubbleSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
await swap(arr, j, j + 1);
}
}
}
}
async function swap(arr, a, b) {
[arr[a], arr[b]] = [arr[b], arr[a]]
console.log(arr);
return waitFor(1000);
}
const array = [10, 9, 4, 5, 3, 1, 2];
bubbleSort(array);
This question already has answers here:
Does return stop a loop?
(7 answers)
Closed 10 months ago.
So, I am learning functions and trying to create a function which takes an array as a parameter.
function printArray(arr){
for (let i = 0; i < arr.length; i++){
let upperCased = arr[i].toUpperCase();
return upperCased;
};
}
const testArray = ['o', 'p'];
printArray(testArray);
However, it returns only the first value 'O'
A return statement only gets executed once, then you exit the function.
You need to update the element on each iteration and, once the loop is complete, return the updated array.
function printArray(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].toUpperCase();
}
return arr;
}
const testArray = ['o', 'p', 'Bob from accounting'];
console.log(printArray(testArray));
This question already has answers here:
Comma after variable assignment in Javascript
(3 answers)
Closed 1 year ago.
I found this example of how to implement a Promise.all method.
function all(iterable){ // take an iterable
// `all` returns a promise.
return new Promise(function(resolve, reject){
let counter = 0; // start with 0 things to wait for
let results = [], i;
for(let p of iterable){
let current = i;
counter++; // increase the counter
Promise.resolve(p).then(function(res){ // treat p as a promise, when it is ready:
results[i] = res; // keep the current result
if(counter === 0) resolve(results) // we're done
}, reject); // we reject on ANY error
i++; // progress counter for results array
}
});
}
I am not sure what is going on with this line of code: let results = [], i;
When I run that in the console i becomes undefined. In the all function they are doing i++, but using that operator on undefined value becomes NaN. What is going on here? If 'i' is undefined, how are they able to use it as an index on an array for results[i] = res; // keep the current result?
let results = [], i;
is equivalent to
let results = [];
let i;
let results = [], i;
is same as:
let results = [];
let i;
i gets the value undefined. Any math on undefined will return NaN not a number.
console.log(undefined + 1);
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I have a little problem here.
My console.log(e) gives me the good result (1 or 2).
but the console.log(test) return me the integer variable.
how can I store the function result in the test variable to use it later please ?
Thx a lot !
const spans = selectPager.getElementsByTagName('span');
const test = function() {
for (let i = 0, len = spans.length; i < len; i++) {
(function(e) {
spans[i].onclick = function() {
console.log(e)
}
})(i);
}
}
test();
console.log(test);
Pass a callback to test, and invoke the callback inside the click handler. There's also no need for the IIFE inside the loop, since you're using let:
const spans = document.getElementsByTagName('span');
const test = function(cb) {
for (let i = 0, len = spans.length; i < len; i++) {
spans[i].onclick = function() {
console.log(i)
cb(i);
};
}
}
test((result) => {
console.log('Outside, have', result);
});
<span>click</span>
<span>click</span>
<span>click</span>
<span>click</span>
<span>click</span>
This question already has answers here:
Waiting for promise in for loop
(2 answers)
Closed 4 years ago.
I have a state this.state = { PathBased : [] , ...ect}
and a function containing a for loop ,after looping this.state.data I want to add every returned element of the for loop to PathBased state ,
I can't find how to do it , could you please help
by the way
console.log(this.state.data) output is 5
async readFromLocal (){
let dirs = RNFetchBlob.fs.dirs;
let path = [];
let leng = this.state.data.length;
if(leng > 0)
{
for( var j = 0 ; j < leng; j++)
{
path[j] = dirs.PictureDir+"/folder/"+this.state.data[j].title;
const xhr = RNFetchBlob.fs.readFile(path[j], 'base64')
.then ((data) => {this.setState({PathBased:[...PathBased,data]})})
.catch ((e) => {e.message});
}
}
console.log(this.state.PathBased.length) // output = 0
}
You could make use of Promise.all and set the final result in the PathBased state. Also since setState is async you need to check the updated state in setState callback.
async readFromLocal (){
let dirs = RNFetchBlob.fs.dirs;
let path = [];
let promises = [];
let leng = this.state.data.length;
if(leng > 0) {
for( let j = 0 ; j < leng; j++) {
path[j] = dirs.PictureDir+"/folder/"+this.state.data[j].title;
promises.push(RNFetchBlob.fs.readFile(path[j], 'base64'))
}
}
Promise.all(promises)
.then(data => this.setState({PathBased: data}, () => {console.log(this.state.PathBased)})
)
.catch(e => {console.log(e.message)});
}