I have the following setup:
const foo = () => {
bar((err,payload) => {
// some stuff happens here
}
}
So I need to continuously call "bar" inside of "foo" until a certain outcome happens in the "some stuff happens here" part. But I obviously have to wait for the outcome of the callback before re-calling "bar" - how could I structure this?
Try using the new await and async in ES6.
const foo = async () => {
var myOutcome;
while (/*CHECK HERE*/) {
try {
myOutcome = await /* call async javascript function here */
} catch (e) {
// Handle error here
}
}
}
This all relies on Javascript Promises, so long as that function returns a promise it will automatically be run more of a synchronous like manner.
Edit if the function only supports callbacks you can wrap it in a promise like so.
function myCallbackFunctionPromise() {
return new Promise((resolve, reject) => {
callbackFunction((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
Related
This question already has answers here:
await setTimeout is not synchronously waiting
(2 answers)
Closed last month.
I have a async fetch function that waits 2 seconds and returns a object:
async function fetch() {
var object;
await setTimeout(() => { object = { name: 'User', data: 'API Data' } }, 2000);
return object;
}
I want to display the object when the initialization is completely done (after 2 seconds)
fetch().then((val) => {
console.log("DONE!");
console.log(val.name);
}).catch((err) => {
console.log("ERROR!");
console.log(err);
});
The code prints both DONE and ERROR Cannot read properties of undefined (reading 'name')
I have tried with Promise, no luck
let promise = new Promise((resolve, reject) => {
let request = fetch();
if (request !== undefined)
resolve(request);
else
reject(request);
}).then((val) => {
console.log(val);
});
How can I properly check that fetch() has returned a value before printing without changing the inside of the function. I can delete the async and await in it but I am unable to edit it (I.E. adding a Promise inside)
Based on requirement
I can delete the async and await in it (fetch function) but I am unable to edit it (I.E. adding a Promise inside)
The only way I see is to override window.setTimeout function to make it to return a promise. That way you will be able to await it and there will be no need to modify your fetch function.
const oldTimeout = window.setTimeout;
window.setTimeout = (fn, ms) => {
return new Promise((resolve, reject) => {
oldTimeout(() => {
fn();
resolve();
}, ms);
});
};
async function fetch() {
var object;
await setTimeout(() => {
object = { name: "User", data: "API Data" };
}, 2000);
return object;
}
fetch()
.then((val) => {
console.log("DONE!");
console.log(val.name);
})
.catch((err) => {
console.log("ERROR!");
console.log(err);
});
NOTE: For anyone without this requirement - please, use other answers to this question or check await setTimeout is not synchronously waiting for additional details/explanations. This kind of overridings are very confusing due to everyone expect common and well-known functions to behavior in a way described in the docs.
You cannot await the setTimeout function, this is because your function returns undefined. You have used the promise in the wrong way. Below code will fix your issue.
function fetch() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ name: "User", data: "API Data" });
}, 2000);
});
}
fetch()
.then((val) => {
console.log("DONE!");
console.log(val.name);
})
.catch((err) => {
console.log("ERROR!");
console.log(err);
});
And remember that there is no need to change the setTimeout function.
The problem is that setTimeout does not actually return a promise, which means you cannot use await with setTimeout, that's why the var object; is returned instantly as undefined.
To solve this issue, you simply need to wrap setTimeout around a promise.
Like so:
function setTImeoutAwait(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
You can then use it like this:
async function fetch() {
var object;
await setTImeoutAwait(1000).then(() => {
object = { name: "test" };
});
return object;
}
When using a simple callback such as in the example below:
test() {
api.on( 'someEvent', function( response ) {
return response;
});
}
How can the function be changed to use async / await? Specifically, assuming 'someEvent' is guaranteed to be called once and only once, I'd like the function test to be an async function which does not return until the callback is executed such as:
async test() {
return await api.on( 'someEvent' );
}
async/await is not magic. An async function is a function that can unwrap Promises for you, so you'll need api.on() to return a Promise for that to work. Something like this:
function apiOn(event) {
return new Promise(resolve => {
api.on(event, response => resolve(response));
});
}
Then
async function test() {
return await apiOn( 'someEvent' ); // await is actually optional here
// you'd return a Promise either way.
}
But that's a lie too, because async functions also return Promises themselves, so you aren't going to actually get the value out of test(), but rather, a Promise for a value, which you can use like so:
async function whatever() {
// snip
const response = await test();
// use response here
// snip
}
It's annoying that there isn't a straightforward solution, and wrapping return new Promise(...) is fugly, but I have found an ok work-around using util.promisify (actually it also kinda does the same wrapping, just looks nicer).
function voidFunction(someArgs, callback) {
api.onActionwhichTakesTime(someMoreArgs, (response_we_need) => {
callback(null, response_we_need);
});
}
The above function does not return anything, yet. We can make it return a Promise of the response passed in callback by doing:
const util = require('util');
const asyncFunction = util.promisify(voidFunction);
Now we can actually await the callback.
async function test() {
return await asyncFunction(args);
}
Some rules when using util.promisify
The callback must be the last argument of the function that is gonna be promisify
The supposed-callback must be in the form (err, res) => {...}
Funny thing is we do not need to ever specifically write what's the callback actually is.
async/await is magic. You can create a function asPromise to handle this kind of situations:
function asPromise(context, callbackFunction, ...args) {
return new Promise((resolve, reject) => {
args.push((err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
if (context) {
callbackFunction.call(context, ...args);
} else {
callbackFunction(...args);
}
});
}
and then use it when you want:
async test() {
return await this.asPromise(this, api.on, 'someEvent');
}
the number of args is variable.
You can achieve this without callbacks , use promise async await instead of callbacks here how I would do this. And also here I have illustrated two methods to handle errors
clickMe = async (value) => {
// begin to wait till the message gets here;
let {message, error} = await getMessage(value);
// if error is not null
if(error)
return console.log('error occured ' + error);
return console.log('message ' + message);
}
getMessage = (value) => {
//returning a promise
return new Promise((resolve, reject) => {
setTimeout(() => {
// if passed value is 1 then it is a success
if(value == 1){
resolve({message: "**success**", error: null});
}else if (value == 2){
resolve({message: null, error: "**error**"});
}
}, 1000);
});
}
clickWithTryCatch = async (value) => {
try{
//since promise reject in getMessage2
let message = await getMessage2(value);
console.log('message is ' + message);
}catch(e){
//catching rejects from the promise
console.log('error captured ' + e);
}
}
getMessage2 = (value) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(value == 1)
resolve('**success**');
else if(value == 2)
reject('**error**');
}, 1000);
});
}
<input type='button' value='click to trigger for a value' onclick='clickMe(1)' />
<br/>
<input type='button' value='click to trigger an error' onclick='clickMe(2)' />
<br/>
<input type='button' value='handling errors with try catch' onclick='clickWithTryCatch(1)'/>
<br/>
<input type='button' value='handling errors with try catch' onclick='clickWithTryCatch(2)'/>
const getprice = async () => {
return await new Promise((resolve, reject) => {
binance.prices('NEOUSDT', (error, ticker) => {
if (error) {
reject(error)
} else {
resolve(ticker);
}
});
})}
router.get('/binanceapi/price', async function (req, res, next) {
res.send(await binanceAPI.getprice());});
I have the following snippet of code inside asynchronous function -
await application.save((err) => {
console.log("hello");
if (err) {
res.status(500).send({ message: "Error encountered" });
}
});
console.log("hey");
Why does "hey" get printed out earlier than "hello"? And how to fix it so the behaviour is as expected (asynchronous save operation is waited for and only when it's done and "hello" is printed, "hey" should be printed).
Following code does actually save object to MongoDB, but when I use application.save().then(() => {}) I get an error "Cannot read property 'then' of undefined"
You are confusing between callbacks and promises.
For example, we have first task F, long task T and next task N. We want to ensure the code run in the order F -> T -> N. To do that, we need either callbacks or promises.
Callbacks
function F() {}
function T(cb) {
// do that long task here
cb(err); // then call the cb and pass is the err
}
function N() {}
function main() {
F();
cb = (err) => {
if (err) { // handle err }
else {
N() // N needs to be run in cb
}
// clean up
// N can also be put here if you want to guarantee N will run
};
T(cb);
}
Promises
function F() {}
function T(cb) {
return new Promise((resolve, reject) => {
// do that long task here
if(err) {
reject();
} else {
resolve();
}
});
}
function N() {}
// using .then .catch .final
function main() {
F();
T().then(N())
.catch(() => {
// handle error
})
.finally(() => {
// clean up
// N can also be put here if you want to guarantee N will run
})
}
// using async/await
async function main() {
F();
try {
await T();
N();
} catch {
// handle error
} finally {
// clean up
// N can also be put here if you want to guarantee N will run
}
}
In your case, save() function does not return a promise but expects a callback to be passed in. If you want a quick and simple solution, put your console.log("hey"); in the callback. A better way is to promisify that callback function so it returns a promise and you can await it. Here is a sample promisify function to turn functions accepting callbacks into functions returning promises:
From
function T(...args, cb) {
// do that long task here
cb(err, data)
}
To
function TAsync(...args) {
return new Promise((resolve, reject) => {
T(...args, function(err, data) {
if (err) reject(err)
else resolve(data)
});
});
}
if a function returns a promise you just need to use the await and assign the return to a variable which is the response. You shoud always use a try catch because promises can launch exceptions.
function divide(i, j) {
return new Promise((resolve, reject) => {
if(j == 0) {
reject("division by zero.");
} else {
resolve(i / j);
}
});
}
async function main() {
try {
let resp = await divide(5, 2);
console.log(`resp = ${resp}`);
resp = await divide(2, 0);
console.log(`resp 2 = ${resp}`);
} catch(e) {
console.log(`catch = ${e}`);
}
}
// another way to use promises
divide(5,2).then((resp) => {
console.log(resp);
}).catch((err) => {
console.log(err);
});
divide(5,0).then((resp) => {
console.log(resp);
}).catch((err) => {
console.log(err);
});
main();
probably your function isn't returning a promise.
I am using async/await to return the Promise , to use it as promoise in node script. When I am trying to make use of the return value as Promise , its giving a error a.then is not a function
here is the sample code
function test () {
//do something .......
//....
return global.Promise;
}
(async ()=> {
let a = await test();
a.then(()=> { console.log('good ')}, (err)=> { console.log()});
})();
The Promise constructor function isn't a promise, it is a tool to make promises with.
Even if it was a promise, since you are awaiting the return value of test, it would have been resolved into a value before you try to call then on it. (The point of await is that it replaces the use of then() callbacks).
You can await a function that returns a promise like this:
function test() {
return new Promise((resolve, reject) => {
if (true) {
reject("Custom error message");
}
setTimeout(() => {
resolve(56)
}, 200);
})
}
async function main() {
try {
const a = await test();
console.log(a)
} catch (e) { // this handles the "reject"
console.log(e);
}
}
main();
If you change the true to false you can test the "resolve" case.
await retrieves the resolved value from a Promise
let a = await test(); // `a` is no longer a Promise
I've put together two ways of retrieving values from a Promise
using await
(async () => {
try {
let a = await test();
console.log('Good', a);
} catch(err) {
console.log(err);
}
})();
using .then()
test().then(a => {
console.log('Good', a);
}).catch(err => {
console.log(err);
});
Please note that, the async arrow function is removed because there is no await needed.
I have the following async function:
async function readFile () {
let content = await new Promise((resolve, reject) => {
fs.readFile('./file.txt', function (err, content) {
if (err) {
return reject(err)
}
resolve(content)
})
})
console.log(content)
}
readFile()
This runs just fine. It outputs the file buffer to the console as expected. But now, if I try to instead return the value:
async function readFile () {
let content = await new Promise((resolve, reject) => {
fs.readFile('./file.txt', function (err, content) {
if (err) {
return reject(err)
}
resolve(content)
})
})
return content
}
console.log(readFile())
I now get:
Promise { <pending> }
Why is this? Why can you use a value inside that function but when you return it out of the function it's now a Promise?
How do you actually make use of this in a normal workflow? For example, lets say I wanted to check if a file exists, then read in the file, then update some database with the content, the synchronous pseudo code would look something like this:
if (fileExists(path)) {
buffer = readFile(path)
updateDatabase(buffer)
}
That workflow consists of 3 individual async operations. How would you do something like this with async/await? Is the key that you have to have your entire script wrapped in an async function?
async function doSomething () {
if (fileExists(path)) {
buffer = readFile(path)
updateDatabase(buffer)
}
}
(Keep in mind that is just pseudo-code but hopefully its gets my point across).
All async functions return a promise as was mentioned in the comments. You could therefore re-write your readFile function like this:
function readFile() {
return new Promise((resolve, reject) => {
fs.readFile('./file.txt', function (err, content) {
if (err) {
return reject(err)
}
resolve(content)
})
})
}
You would then consume the return value of readFile via await:
console.log(await readFile()) // will log your actual file contents.
The usual workflow with this paradigm is to break your async operations into separate functions that each return a promise, and then run them all inside a broader async function, much like you suggest, but with awaits and some error handling like so:
async function doSomething () {
try {
const fileCheck = await fileExists(path)
if (fileCheck) {
const buffer = await readFile(path)
await updateDatabase(buffer)
// Whatever else you want to do
}
} catch (err) {
// handle any rejected Promises here.
}
}
const serchContentXmlFile = async (path, content) => {
return new Promise((resolve, reject) => {
fs.readFile(path, function (err, data) {
if (err) {
return reject(err)
}
resolve(data.indexOf(content))
})
})
}
await serchContentXmlFile("category.xml",xmlUrl);