Problem: Asynchronous code causes whole source code to follow asynchrony
Example:
// global scope
let _variableDefinedInParentScope
WriteConfiguration(__params) {
// overSpreading.
let { data, config } = __params
// local variable.
let _fileName, _configuration, _write, _read
// variable assignment.
_fileName = config
_configuration = data
// if dataset and fileName is not empty.
if(!_.isEmpty(_configuration) && !_.isEmpty(_fileName)) {
// create a path you want to write to
// :warning: on iOS, you cannot write into `RNFS.MainBundlePath`,
// but `RNFS.DocumentDirectoryPath` exists on both platforms and is writable
_fileName = Fs.DocumentDirectoryPath + ' /' + _fileName;
// get file data and return.
return Fs.readDir(_fileName).then((__data) => {
console.error(__data)
// if data is not empty.
if(!_.isEmpty(__data)) {
// return data if found.
return __data
} else {
// write the file
return Fs.writeFile(_fileName, data, 'utf8')
.then((success) => {
// on successful file write.
return success
})
.catch((err) => {
// report failure.
console.error(err.message);
})
}
})
.catch((err) => {
// report failure.
console.error(err.message)
})
}
} // write configuration to json file.
following are ways to promise handling
.then((__onAccept)=>{}, (__onReject) => {})
aync function (__promise) { await WriteConfiguration() }
.then((_onAccept) => { _variableDefinedInParentScope = __onAccept }
As far i know third one is useless point as i never encounterd any return because promise is resolving takes time and calling that variable before any resolve will return undefined
React-native
In react-native almost every part of code is syncronus where file writing module's are asynchrony and this is causing trouble for me.
What i want
i want to return value from asyncrous to syncrouns code. without any asynchrony chain.
Your answer is quit simple by using the
await
and
async
EXAMPLE:
mainFunction(){
//will wait for asyncroFunction to finish!!
await asyncroFunction()
}
async asyncroFunction(){
}
Related
When calling a function that returns a promise, comes back as undefined unless async operators are removed, then returns ZoneAwarePromise, but contains no data.
I know the query returns data when the function executes, it however does not seem to pass that data to the actual return part of the function call.
I have looked at several Stack questions that have not answered this question including this question:
Async/Await with Request-Promise returns Undefined
This is using a REST endpoint to pull data, the console.logs do show the data is correct, however return comes back as undefined
this.allPeople.forEach(async person => {
const dodString = await this.getRelatedRecords(person); //undefined
}
This is the main function that returns a promise / data
async getRelatedRecords(person) {
// function truncated for clarity
// ...
//
console.warn('This async should fire first');
selPeopleTable.relationships.forEach(relationship => {
allRelationshipQueries.push(
arcgisService.getRelatedTableData(
selPeopleTable.url, [person[oidField.name]], relationship.id, relationship.name),
);
});
await Promise.all(allRelationshipQueries).then(allResults => {
console.log('Inside the Promise');
// The Specific node I am looking for
const data = allResults[1].results.relatedRecordGroups[0].relatedRecords[0].attributes.dod;
console.log(data); // Shows correctly as the data I am looking for
return data;
}).catch(function(data){
console.log('there might be data missing', data);
});
}
Removing the ASYNC operators cause the getRelatedRecords() to fire after the containing function and / or return a 'ZoneAwarePromise' which contains no data. I need getRelatedRecords() to fire first, then to run the rest of the code.
I can provide more snippets if need be.
Zone Aware Promise
When the Async operators are (I think) setup correctly
You need to return this as well:
await Promise.all(allRelationshipQueries).then(allResults => {
console.log('Inside the Promise');
// The Specific node I am looking for
const data = allResults[1].results.relatedRecordGroups[0].relatedRecords[0].attributes.dod;
console.log(data); // Shows correctly as the data I am looking for
return data;
})
return in the above block is returning but all of this is in the scope of the arrow function which is then(allResults => { so you also need to return this function like this:
return await Promise.all(allRelationshipQueries).then(allResults => {
Approach #2:
Second way would be to store that into variable like this:
let dataToReturn = await Promise.all(allRelationshipQueries).then(allResults => {
console.log('Inside the Promise');
// The Specific node I am looking for
const data = allResults[1].results.relatedRecordGroups[0].relatedRecords[0].attributes.dod;
console.log(data); // Shows correctly as the data I am looking for
return data;
}).catch(function(data){
console.log('there might be data missing', data);
});
return dataToReturn;
I've read MANY articles, but I'm totally a newbie to this whole async thing and am having a very hard time wrapping my brain around how it all works. I want to map the filtered array of objects, and inside that, I'd like to return the result of a function (an amount) and set that as the value of pmtdue. I tried this a bunch of ways, but always get zoneawarepromise or observable when it's logged, or a ton of errors. This is probably the closest I've gotten, but it's still not right.
async today(day = null, status = null) {
this.logger.log(`show today's ${status} appts ${day}`);
// filter master list for today
const filtered = [...this.apptList].filter(appt => {
if (!status) {
return (
appt.scheduled >= this.helperService.dayStart(day) &&
appt.scheduled <= this.helperService.dayEnd(day) &&
appt.status.status !== 'Checked Out' &&
appt.status.status !== 'Scheduled'
);
} else {
return (
appt.scheduled >= this.helperService.dayStart(day) &&
appt.scheduled <= this.helperService.dayEnd(day) &&
appt.status.status === status
);
}
});
// calculate due amount and map it to pmtdue field
const dueappts = await this.getTotalDue(filtered).then(
res => {
// console.log(res);
this.ApptModels = res;
},
err => {
console.log(err);
}
);
// send the data to ng2-smart-table
console.log(`filtered ApptModels`, this.ApptModels);
}
This is the function that does the mapping and has the functions I want to work
// a.pmtduedate returns the correct value as there is no http call
// a.pmtdue returns a zoneawarepromise but I don't know how to get the VALUE
getTotalDue(appts: Array<any>): Promise<any> {
return Promise.all(
appts.map(async (a: any) => {
a.pmtduedate = await this.helperService.getDueDate(a);
a.pmtdue = await this.dataService.sendTotalDue(a);
console.log(a.pmtdue); // logs undefined
return a;
})
);
}
My data service function (I know sometimes code matters that I think is insignificant):
async sendTotalDue(appt) {
this.logger.log(`fetch amount ${appt.patientID.nickname} owes`);
return await this.http.post(`${SERVER_URL}/sendtotaldue`, appt);
}
And finally, the backend function(minus details on data). It logs the correct amount on the backend, I just can't get it to display on the frontend:
module.exports.sendTotalDue = (req, res) => {
const appt = req.body;
// callback function that handles returning data
function done(err, results) {
const totaldue = parseInt(results, 10);
console.log(`API sendTotalDue CALLBACK done...totaldue: ${totaldue}`);
if (err) {
console.log('ERROR getting total due: callback error', err);
res.sendStatus(500).json(err); // server error; it'd be good to be more specific if possible
} else {
// end the request, send totaldue to frontend
console.log(`SUCCESS send totaldue to frontend ${totaldue}`);
res.status(200).json(totaldue);
}
}
// run first function
console.log(`1. getAmtDue:`);
this.getAmtDue(appt, done);
};
module.exports.getAmtDue(appt, callback) {
... function finds past visits, past payment and due totals
}
module.exports.getCurrentDue(appt, pastdueamt, callback) {
... function finds current visits and payments. calculates current due and adds the past due
callback(null, totaldue);
}
Can someone please help me understand what I'm doing wrong? Feel free to dumb it down for me, cause that's how I feel at this point.
EDITED TO FIX ERRORS like missing await and return. It is now to the point where I can see the value returned in the data service, but I get undefined in the map function section.
Ooooh!!! I GOT IT! I still don't totally understand WHY it works, but I changed the data service as follows:
async sendTotalDue(appt): Promise<any> {
this.logger.log(`fetch amount ${appt.patientID.nickname} owes`);
try {
const result = await this.http
.post(`${SERVER_URL}/sendtotaldue`, appt)
.toPromise();
return result as any[];
} catch (error) {
console.log(error);
}
}
Changing my service to the above finally got my values to appear exactly where I wanted them in the data table! :)
I found this article, which helped figure out how to work with Observable
Angular Tutorial with Async and Await
I have this piece of code in my angular 6 application:
publish() {
change.subscribe((result: boolean) => {
if(!result) return; // exit publish function
});
// continue
}
I want this publish function to continue executing only if result is true.
How to manage this ?
it is impossible, you should put your publish function code inside your subscription, or there is another way you can do, you can use .toPromise() and async/await, if you will get your data one time and not in a stream
async publish() {
const result = await change.toPromise();
if(result) {
// your publish function code here
});
}
Converting observable to promise is always a bad idea, so better is just to create local variable and assign a value from yourObservable to this local variable.
async publish() {
let doBreak = false;
yourObservable.subscribe((result) => {
if (!result) {
doBreak = true;
}
}
if (doBreak) {
return;
}
}
I'm trying to get my head around promises, I think I can see how they work in the way that you can say do Step 1, Step 2 and then Step 3 for example.
I have created this download function using node-fetch (which uses native Promises)
## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');
module.exports = function(url, target) {
fetch(url)
.then(function(res) {
var dest = fs.createWriteStream(target);
res.body.pipe(dest);
}).then(function(){
console.log(`File saved at ${target}`)
}).catch(function(err){
console.log(err)
});
}
So this all executes in order and I can see how that works.
I have another method that then converts a CSV file to JSON (again using a promise)
## CSVToJson.js
const csvjson = require('csvjson');
const fs = require('fs');
const write_file = require('../helpers/WriteToFile');
function csvToJson(csv_file, json_path) {
return new Promise(function(resolve, reject) {
fs.readFile(csv_file, function(err, data){
if (err)
reject(err);
else
var data = data.toString();
var options = {
delimiter : ',',
quote : '"'
};
const json_data = csvjson.toObject(data, options);
write_file(json_path, json_data)
resolve(data);
});
});
}
module.exports = {
csvToJson: csvToJson
}
When I call these functions one after another the second function fails as the first has not completed.
Do I need to wrap these two function calls inside another promise, even though on their own they each have promises implemented?
Please advise if I am totally misunderstanding this
When I call these functions one after another the second function fails as the first has not completed.
There are two issues with the first:
It doesn't wait for the file to be written; all it does is set up the pipe, without waiting for the process to complete
It doesn't provide any way for the caller to know when the process is complete
To deal with the first issue, you have to wait for the finish event on the destination stream (which pipe returns). To deal with the second, you need to return a promise that won't be fulfilled until that happens. Something along these lines (see ** comments):
module.exports = function(url, target) {
// ** Return the end of the chain
return fetch(url)
.then(function(res) {
// ** Unfortunately, `pipe` is not Promise-enabled, so we have to resort
// to creating a promise here
return new Promise((resolve, reject) => {
var dest = fs.createWriteStream(target);
res.body.pipe(dest)
.on('finish', () => resolve()) // ** Resolve on success
.on('error', reject); // ** Reject on error
});
}).then(result => {
console.log(`File saved at ${target}`);
return result;
});
// ** Don't `catch` here, let the caller handle it
}
Then you can use then and catch on the result to proceeed to the next step:
theFunctionAbove("/some/url", "some-target")
.then(() = {
// It worked, do the next thing
})
.catch(err => {
// It failed
});
(Or async/await.)
Side note: I haven't code-reviewed it, but a serious issue in csvToJson jumped out, a minor issue as well, and #Bergi has highlighted a second one:
It's missing { and } around the else logic
The minor issue is that you have var data = data.toString(); but data was a parameter of that function, so the var is misleading (but harmless)
It doesn't properly handle errors in the part of the code in the else part of the readFile callback
We can fix both by doing a resolve in the else and performing the rest of the logic in a then handler:
function csvToJson(csv_file, json_path) {
return new Promise(function(resolve, reject) {
fs.readFile(csv_file, function(err, data){
if (err)
reject(err);
else
resolve(data);
});
})
.then(data => {
data = data.toString();
var options = {
delimiter : ',',
quote : '"'
};
const json_data = csvjson.toObject(data, options);
write_file(json_path, json_data);
return data;
});
}
I have a function I want to execute in the page using chrome.tabs.executeScript, running from a browser action popup. The permissions are set up correctly and it works fine with a synchronous callback:
chrome.tabs.executeScript(
tab.id,
{ code: `(function() {
// Do lots of things
return true;
})()` },
r => console.log(r[0])); // Logs true
The problem is that the function I want to call goes through several callbacks, so I want to use async and await:
chrome.tabs.executeScript(
tab.id,
{ code: `(async function() {
// Do lots of things with await
return true;
})()` },
async r => {
console.log(r); // Logs array with single value [Object]
console.log(await r[0]); // Logs empty Object {}
});
The problem is that the callback result r. It should be an array of script results, so I expect r[0] to be a promise that resolves when the script finishes.
Promise syntax (using .then()) doesn't work either.
If I execute the exact same function in the page it returns a promise as expected and can be awaited.
Any idea what I'm doing wrong and is there any way around it?
The problem is that events and native objects are not directly available between the page and the extension. Essentially you get a serialised copy, something like you will if you do JSON.parse(JSON.stringify(obj)).
This means some native objects (for instance new Error or new Promise) will be emptied (become {}), events are lost and no implementation of promise can work across the boundary.
The solution is to use chrome.runtime.sendMessage to return the message in the script, and chrome.runtime.onMessage.addListener in popup.js to listen for it:
chrome.tabs.executeScript(
tab.id,
{ code: `(async function() {
// Do lots of things with await
let result = true;
chrome.runtime.sendMessage(result, function (response) {
console.log(response); // Logs 'true'
});
})()` },
async emptyPromise => {
// Create a promise that resolves when chrome.runtime.onMessage fires
const message = new Promise(resolve => {
const listener = request => {
chrome.runtime.onMessage.removeListener(listener);
resolve(request);
};
chrome.runtime.onMessage.addListener(listener);
});
const result = await message;
console.log(result); // Logs true
});
I've extended this into a function chrome.tabs.executeAsyncFunction (as part of chrome-extension-async, which 'promisifies' the whole API):
function setupDetails(action, id) {
// Wrap the async function in an await and a runtime.sendMessage with the result
// This should always call runtime.sendMessage, even if an error is thrown
const wrapAsyncSendMessage = action =>
`(async function () {
const result = { asyncFuncID: '${id}' };
try {
result.content = await (${action})();
}
catch(x) {
// Make an explicit copy of the Error properties
result.error = {
message: x.message,
arguments: x.arguments,
type: x.type,
name: x.name,
stack: x.stack
};
}
finally {
// Always call sendMessage, as without it this might loop forever
chrome.runtime.sendMessage(result);
}
})()`;
// Apply this wrapper to the code passed
let execArgs = {};
if (typeof action === 'function' || typeof action === 'string')
// Passed a function or string, wrap it directly
execArgs.code = wrapAsyncSendMessage(action);
else if (action.code) {
// Passed details object https://developer.chrome.com/extensions/tabs#method-executeScript
execArgs = action;
execArgs.code = wrapAsyncSendMessage(action.code);
}
else if (action.file)
throw new Error(`Cannot execute ${action.file}. File based execute scripts are not supported.`);
else
throw new Error(`Cannot execute ${JSON.stringify(action)}, it must be a function, string, or have a code property.`);
return execArgs;
}
function promisifyRuntimeMessage(id) {
// We don't have a reject because the finally in the script wrapper should ensure this always gets called.
return new Promise(resolve => {
const listener = request => {
// Check that the message sent is intended for this listener
if (request && request.asyncFuncID === id) {
// Remove this listener
chrome.runtime.onMessage.removeListener(listener);
resolve(request);
}
// Return false as we don't want to keep this channel open https://developer.chrome.com/extensions/runtime#event-onMessage
return false;
};
chrome.runtime.onMessage.addListener(listener);
});
}
chrome.tabs.executeAsyncFunction = async function (tab, action) {
// Generate a random 4-char key to avoid clashes if called multiple times
const id = Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
const details = setupDetails(action, id);
const message = promisifyRuntimeMessage(id);
// This will return a serialised promise, which will be broken
await chrome.tabs.executeScript(tab, details);
// Wait until we have the result message
const { content, error } = await message;
if (error)
throw new Error(`Error thrown in execution script: ${error.message}.
Stack: ${error.stack}`)
return content;
}
This executeAsyncFunction can then be called like this:
const result = await chrome.tabs.executeAsyncFunction(
tab.id,
// Async function to execute in the page
async function() {
// Do lots of things with await
return true;
});
This wraps the chrome.tabs.executeScript and chrome.runtime.onMessage.addListener, and wraps the script in a try-finally before calling chrome.runtime.sendMessage to resolve the promise.
Passing promises from page to content script doesn't work, the solution is to use chrome.runtime.sendMessage and to send only simple data between two worlds eg.:
function doSomethingOnPage(data) {
fetch(data.url).then(...).then(result => chrome.runtime.sendMessage(result));
}
let data = JSON.stringify(someHash);
chrome.tabs.executeScript(tab.id, { code: `(${doSomethingOnPage})(${data})` }, () => {
new Promise(resolve => {
chrome.runtime.onMessage.addListener(function listener(result) {
chrome.runtime.onMessage.removeListener(listener);
resolve(result);
});
}).then(result => {
// we have received result here.
// note: async/await are possible but not mandatory for this to work
logger.error(result);
}
});
For anyone who is reading this but using the new manifest version 3 (MV3), note that this should now be supported.
chrome.tabs.executeScript has been replaced by chrome.scripting.executeScript, and the docs explicitly state that "If the [injected] script evaluates to a promise, the browser will wait for the promise to settle and return the resulting value."