Change to async/await syntax - javascript

I have some code that print in console a number series start for 1,
continuing for 2 and so on. I've done it with promises but now I want to change my promise script to async/await mode, but It doesn't work.
What I tried was this:
const alwaysThrows = () => {
throw new Error("OH NOES");
};
const iterate = (integer) => {
console.log(integer);
return integer + 1;
};
const prom = Promise.resolve(iterate(1));
const manageOk = async () => {
let result = await prom;
console.log(result);
}
manageOk()
but I dont know how get the rest of numbers.
This is my original code:
const alwaysThrows = () => {
throw new Error("OH NOES");
};
const iterate = (integer) => {
console.log(integer);
return integer + 1;
};
const prom = Promise.resolve(iterate(1));
prom
.then((value) => iterate(value))
.then(iterate)
.then(iterate)
.then(iterate)
.then(alwaysThrows)
.then(iterate)
.then(iterate)
.then(iterate)
.catch(e => console.log(e.message));

const manageOk = async (val) => {
return await iterate(val);
}
manageOk(1)
.then(res => manageOk(res))
.then(manageOk)
.then(manageOk)
.then(manageOk)

Related

How to write await() for multiple promises in JavaScript?

I m trying to write await for multiple promises, instead of nested functions.
Please take a look at the below code i tried, as it will explain better than me.
var main = async () => {
// const main_ = await Promise.all(fun1,fun2,fun3);
// Fun 3
const fun3 = () =>
new Promise((resolve) => async () => {
// console.log(1);
return resolve(await fun2(1));
});
// Fun 2
const fun2 = (value) =>
new Promise((resolve) => async (value) => {
value = value + 1;
// console.log(value);
return resolve(await fun1(value));
});
// Fun 1
const fun1 = () =>
new Promise((resolve) => (value) => {
value = value + 1;
// console.log(value);
return resolve(value);
});
fun3();
};
main();
I tried console logging to debut but I m getting nothing in the console.
Any help is greatly appreciated.
the syntax is wrong, its not new Promise((resolve) => async () => {}) with 2 arrow, but new Promise((resolve) => {}) also you can call promise function without await
var main = async () => {
// const main_ = await Promise.all(fun1,fun2,fun3);
// Fun 3
const fun3 = () => new Promise(resolve => {
//console.log(1);
return resolve(fun2(1));
});
// Fun 2
const fun2 = (value) => new Promise(resolve => {
value = value + 1;
//console.log(value);
return resolve(fun1(value));
});
// Fun 1
const fun1 = (value) => new Promise(async (resolve) => {
value = value + 1;
console.log('sleep 3 seconds');
await new Promise(r => setTimeout(r, 3000));
console.log(value);
return resolve(value);
});
fun3();
};
main();
If you want to call await inside a Promise callback, you can do this:
const p = new Promise((resolve) => {
(async () => {
const res = await anotherPromise();
resolve(res);
})();
});
So with this in mind, you can rewrite your functions like this:
var main = async () => {
// const main_ = await Promise.all(fun1,fun2,fun3);
// Fun 3
const fun3 = () =>
new Promise((resolve) => {
(async () => {
resolve(await fun2(1));
})();
});
// Fun 2
const fun2 = (value) =>
new Promise((resolve) => {
value = value + 1;
(async () => {
resolve(await fun1(value));
})();
});
// Fun 1
const fun1 = (value) =>
new Promise((resolve) => {
value = value + 1;
(async () => {
resolve(value);
})();
});
return await fun3();
};
// ans: 3
console.log(await main());
If you want to do it in pure async/await, you may do this:
const main = async () => {
const fun1 = async (value) => value + 1;
const fun2 = async (value) => await fun1(value + 1);
const fun3 = async () => await fun2(1);
return await fun3();
}
// output: 3
console.log(await main());
I hope this example works for you.
console.clear();
function wait(ms, data) {
return new Promise( resolve => setTimeout(resolve.bind(this, data), ms) );
}
/**
* These will be run in series, because we call
* a function and immediately wait for each result,
* so this will finish in 1s.
*/
async function series() {
return {
result1: await wait(500, 'seriesTask1'),
result2: await wait(500, 'seriesTask2'),
}
}
/**
* While here we call the functions first,
* then wait for the result later, so
* this will finish in 500ms.
*/
async function parallel() {
const task1 = wait(500, 'parallelTask1');
const task2 = wait(500, 'parallelTask2');
return {
result1: await task1,
result2: await task2,
}
}
async function taskRunner(fn, label) {
const startTime = performance.now();
console.log(`Task ${label} starting...`);
let result = await fn();
console.log(`Task ${label} finished in ${ Number.parseInt(performance.now() - startTime) } miliseconds with,`, result);
}
void taskRunner(series, 'series');
void taskRunner(parallel, 'parallel');
fun3() is an async function so you have to put await before the call.
var main = async () => {
// Fun 3
const fun3 = () => new Promise(resolve => {
//console.log(1);
return resolve(fun2(1));
});
// Fun 2
const fun2 = (value) => new Promise(resolve => {
value = value + 1;
//console.log(value);
return resolve(fun1(value));
});
// Fun 1
const fun1 = (value) => new Promise(async (resolve) => {
value = value + 1;
console.log('sleep 3 seconds');
await new Promise(r => setTimeout(r, 3000));
console.log(value);
return resolve(value);
});
await fun3();
};
main();

How to make result of Promise all in order

Question:
the output of case1 is from 0 to 4 which is in order while
the output of case2 is in random.
I know the reason why case1's result is in order is that the request is send after the result of previous request comes.
In case2 the request will not wait the result of previous request.
my question is that is there a way to retain the result of case2 in order too?
case1
const main = async () => {
const arr = Array.of(...[1,2,3,4,5])
for (let i=0;i<arr.length;i++) {
console.log(`request:${i}`)
const res = await request(i)
console.log(res)
}
console.log("next step")
}
const request = (i:number):Promise<number> => {
return new Promise<number>(((resolve, reject) => {
setTimeout(()=>{
resolve(i)
},Math.random() * 1000)
}))
}
output1
closure
request:0
0
request:1
1
request:2
2
request:3
3
request:4
4
next step
case2
const main = async () => {
const arr = Array.of(...[1,2,3,4,5])
await Promise.all(arr.map(async (v,i) => {
console.log(`request:${v}`)
const res = await request(v)
console.log(`result:${res}`)
console.log(res)
})).catch((e) => {
})
console.log("next step")
}
const request = (i:number):Promise<number> => {
return new Promise<number>(((resolve, reject) => {
setTimeout(()=>{
resolve(i)
},Math.random() * 1000)
}))
}
main()
output2
request:1
request:2
request:3
request:4
request:5
result:4
4
result:5
5
result:1
1
result:3
3
result:2
2
next step
Promise.all() returns an array of the results in the same order; they just won't resolve in order. You could return the response within your request promise, and...
const [result1, result2, result3] = await Promise.all([promise1, promise2, promise3]);
Or if you wanted to iterate over an array...
const results = await Promise.all([promise1, promise2, promise3]);
Promise All should be array of request or promise, in map() should return request.
try this
const main = () => {
const arr = Array.of(...[1,2,3,4,5])
Promise.all(arr.map((v,i) => {
console.log(`request:${v}`)
return request(v)
})).then((res)=>{
res.forEach((val)=>{
console.log(`result:${val}`)
})
}).catch((e) => {
})
console.log("next step")
}
const request = (i)=> {
return new Promise((resolve, reject) => {
setTimeout(()=>{
resolve(i)
}, Math.floor(Math.random() * 10)*1000)
})
}
main()

Promise.all() to await the return of an object property

Inside an async function i have a loop and inside this loop i need to use await to resolve a promise from another async function.
async function smallestCities(states) {
const citiesInState = [];
for (const state of states) {
const length = await lengthOfState(state.Sigla);
const stateObject = {
state: state.Sigla,
cities: length,
};
citiesInState.push(stateObject);
}
citiesInState.sort((a, b) => {
if (a.cities > b.cities) return 1;
if (a.cities < b.cities) return -1;
return 0;
});
return citiesInState.filter((_, index) => index < 5).reverse();
}
It's work fine, but eslint says to disallow await inside of loops and use Promise.all() to resolve all promises.
The problem is that my promises are in an object property:
How can i figure out to use Promise.all() with properties of an object?
Chain a .then onto the lengthOfState call to make the whole Promise resolve to the object you need, inside the Promise.all:
const citiesInState = await Promise.all(
states.map(
state => lengthOfState(state.Sigla).then(cities => ({ state: state.Sigla, cities }))
)
);
const NEW_LAND = 'newLand'
const ACTUAL_FINLAND = 'actualFinland'
const PIRKKAS_LAND = 'pirkkasLand'
const STATE_CITY_MAP = {
[NEW_LAND]: ['HELSINKI', 'VANTAA', 'KORSO'],
[ACTUAL_FINLAND]: ['TURKU'],
[PIRKKAS_LAND]: ['WHITE RAPIDS', 'NOKIA'],
}
const mockGetCities = (stateName) => new Promise((res) => {
setTimeout(() => { res([stateName, STATE_CITY_MAP[stateName]]) }, 0)
})
const compareStatesByCityQty = (a, b) => {
if (a[1].length > b[1].length) return 1
if (a[1].length < b[1].length) return -1
return 0
}
const getSmallestStates = async (stateNames, cityQty) => {
const cities = await Promise.all(stateNames.map(mockGetCities))
return cities
.sort(compareStatesByCityQty)
.reverse()
.slice(0, cityQty)
}
;(async () => {
const stateNames = [NEW_LAND, ACTUAL_FINLAND, PIRKKAS_LAND]
const smallestStates = await getSmallestStates(stateNames, 2)
console.log(smallestStates)
})()

Unexpected `await` inside a loop. (no-await-in-loop)

How Should I await for bot.sendMessage() inside of loop?
Maybe I Need await Promise.all But I Don't Know How Should I add to bot.sendMessage()
Code:
const promise = query.exec();
promise.then(async (doc) => {
let count = 0;
for (const val of Object.values(doc)) {
++count;
await bot.sendMessage(msg.chat.id, `💬 ${count} and ${val.text}`, opts);
}
}).catch((err) => {
if (err) {
console.log(err);
}
});
Error:
[eslint] Unexpected `await` inside a loop. (no-await-in-loop)
If you need to send each message one-at-a-time, then what you have is fine, and according to the docs, you can just ignore the eslint error like this:
const promise = query.exec();
promise.then(async doc => {
/* eslint-disable no-await-in-loop */
for (const [index, val] of Object.values(doc).entries()) {
const count = index + 1;
await bot.sendMessage(msg.chat.id, `💬 ${count} and ${val.text}`, opts);
}
/* eslint-enable no-await-in-loop */
}).catch(err => {
console.log(err);
});
However, if there is no required order for sending the messages, you should do this instead to maximize performance and throughput:
const promise = query.exec();
promise.then(async doc => {
const promises = Object.values(doc).map((val, index) => {
const count = index + 1;
return bot.sendMessage(msg.chat.id, `💬 ${count} and ${val.text}`, opts);
});
await Promise.all(promises);
}).catch(err => {
console.log(err);
});
Performing await inside loops can be avoided once iterations doesn't have dependency in most cases, that's why eslint is warning it here
You can rewrite your code as:
const promise = query.exec();
promise.then(async (doc) => {
await Promise.all(Object.values(doc).map((val, idx) => bot.sendMessage(msg.chat.id, `💬 ${idx + 1} and ${val.text}`, opts);)
}).catch((err) => {
if (err) {
console.log(err);
}
});
If you still and to send one-after-one messages, your code is ok but eslint you keep throwing this error
I had a similar issue recently, I was getting lintting errors when trying to run an array of functions in a chain as apposed to asynchronously.
and this worked for me...
const myChainFunction = async (myArrayOfFunctions) => {
let result = Promise.resolve()
myArrayOfFunctions.forEach((myFunct) => {
result = result.then(() => myFunct()
})
return result
}
I am facing the same issue when I used await inside forEach loop. But I tried with recursive function call to iterate array.
const putDelay = (ms) =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});
const myRecursiveFunction = async (events, index) => {
if (index < 0) {
return;
}
callAnotherFunction(events[index].activity, events[index].action, events[index].actionData);
await putDelay(1);
myRecursiveFunction(events, index - 1);
};

Node JS: chaining promises which are using promises

I need to chain promises which are using request promises, so it is kinda chaining nested promises.
Imagine the code:
const rp = require('request-promise');
function doStuff(){
for ( let i = 0; i <= 10; i++ ){
methodA();
}
};
function methodA(){
let options = {...};
rp(options)
.then(result => methodB(result))
.catch(err => console.log(err));
};
function methodB(resultA){
let options = {uri: resultA};
rp(options)
.then(result => methodC(resultA, result))
.catch(err => console.log(err));
};
function methodC(resultA, resultB){
//some calculations
};
In doStuff I need to wait for result of all ten executions of methodC and collect them into array. I have tried to chain it like that:
function doStuff(){
for ( let i = 0; i <= 10; i++ ){
let promiseA = new Promise((resolve, reject) => {
resolve(methodA());
});
let promiseB = promiseA.then(result => methodB(result));
let promiseC = promiseB.then(result => methodC(promiseA.result, result));
Promise.all([promiseA, promiseB, promiseC]);
}
};
But for sure it won't work, because in methodA and methodB we have HTTP requests which are asynchronous. Therefore, result in promiseB is undefined.
It means, the question is: how to chain promises, if they have nested promises? (and how to collect result in the end?)
Thanks!
UPDATE: Chaining promises also not much of the help, as 1 is returned prior array of AB's, but desired result is vice versa:
function methodA(){
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Resolved A');
resolve('A');
}, Math.random() * 2000);
});
return promise
.then(result => methodB(result))
.catch(err => console.log(err));
}
function methodB(resultA){
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Resolved B');
resolve('B');
}, Math.random() * 2000);
});
return promise
.then(result => methodC(resultA, result))
.catch(err => console.log(err));
}
function methodC(resultA, resultB){
return resultA + resultB;
}
function doStuff() {
let promises = [];
for (let i = 0; i <= 10; i++){
promises.push(methodA());
}
Promise.all(promises).then(results => {
console.log(results);
});
return 1;
}
console.log(doStuff());
Each of your functions needs to return their promise:
function methodA(){
let options = {...};
return rp(options)
.then(result => methodB(result))
.catch(err => console.log(err));
}
function methodB(resultA){
let options = {uri: resultA};
return rp(options)
.then(result => methodC(resultA, result))
.catch(err => console.log(err));
}
function methodC(resultA, resultB){
//some calculations
}
function doStuff() {
let promises = [];
for ( let i = 0; i <= 10; i++ ){
promises.push(methodA());
}
Promise.all(promises).then(...)
}
Edit: I created a test example, which creates promises in methodA and methodB. Each promise lasts some amount of time from 0 to 2 seconds. It seems to be working:
function methodA(){
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Resolved A');
resolve('A');
}, Math.random() * 2000);
});
return promise
.then(result => methodB(result))
.catch(err => console.log(err));
}
function methodB(resultA){
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Resolved B');
resolve('B');
}, Math.random() * 2000);
});
return promise
.then(result => methodC(resultA, result))
.catch(err => console.log(err));
}
function methodC(resultA, resultB){
return resultA + resultB;
}
function doStuff() {
let promises = [];
for (let i = 0; i <= 10; i++){
promises.push(methodA());
}
return Promise.all(promises).then(results => {
console.log(results);
return 1;
});
}
doStuff().then(result => {
console.log(result);
});
Answer by #Frank_Modica is the way to go.
Just want to add that if you enable async/await you could do it like this. But it does require Babel or Typescript:
async function myMethod() {
const options = { }
try {
const result_a = await rp(options)
const result_b = await rp({ uri: result_a })
const result_c = ...
} catch(err) {
console.log(err)
}
}
for (let i = 0; i <= 10; i++) {
await myMethod();
}
It has to be lightly changed to:
Promise.all([promiseA, promiseB, promiseC]).then([promiseD]);
Also in the functions itself it has to be a return statement to make them chained. For the request itself, just add: {async: false}
Also it can be used:
var runSequence = require('run-sequence');
function methodA () {
return runSequence(
'promiseA',
'promiseB',
['promiseC1', 'promiseC2'],
'promiseD',
callback
);
}

Categories