I tried to save some data to chrome local storage. I've been using this ever since and its working fine. However, just yesterday it stops working.
chrome.storage.local.set({ 'test': 'this is an awesome test' }, res => {
if (chrome.runtime.lastError) {
console.log('runtime errorsss');
}
console.log('Response: ', res);
});
This doesn't even return any error. And whatever processes I have after this code is not called. I know this is asynchronous, but my problem really is why it doesn't process the storing and return any Promise.
Please let me know if you have any idea why this is happening. Thanks
Related
I am working with MySQL server, building a NodeJS server.
SomeWhere in the code I have async code that is not waiting, I believe its has something to do with the forEach function.
Is there anything wrong with my implementation of my next function:
async addResponsesToTasks(input, response, isFromCache) {
if (!isFromCache) {
this.saveResponseToCache(input, response);
}
console.log("===7===");
await response.forEach(async (pokemon) => {
console.log("===8===", pokemon);
await this.addTaskToFile(pokemon, false);
console.log("===13===");
});
return true;
}
And this is the output shows that it is not waiting for creation and save in the DB to finish, and jump to do some other things:
Prints of the output - can see 10,12,13,14,15 and only then 11
Hope you could maybe spot what I am missing.
Thanks in advance!
What's happening here is more of a JavaScript thing than a Sequelize thing.
The await is being applied to the lines of code that follow Item.create() inside of this function, but outer functions are continuing to execute.
console.log('9')
saveTaskToDb(task)
console.log('12')
In this code, '12' is going to get logged out before your '11', because this outer code is going to continue to execute, even if the code in saveTaskToDb is awaiting the resolution of the create() method.
To solve this, you'll either need to move all of your asynchronous code into the same code block, or you'll need to return your own promise in the saveTaskToDb function, and await saveTaskToDb.
So Solution was not using forEach, rather using for of loop like that:
async addResponsesToTasks(input, response, isFromCache) {
if (!isFromCache) {
this.saveResponseToCache(input, response);
}
for (const pokemon of response) {
await this.addTaskToFile(pokemon, false);
}
return true;
}
Based on this question: Using async/await with a forEach loop
My app generates several files in parallel that I finally have to concat before serving it to the user.
Some of these can be big (>10M).
In order to achieve this, I have create 2 routines, one for handling the set of files to process and one for appending the content of a file to a destination one. Everything works fine on small/medium size files, but on large ones, the content is truncated...
function copyFileContent(ws,rs){
let errorDetected=false;
return new Promise((resolve,reject)=>{
if(rs && ws){
ws.on('error',(err)=>{
errorDetected=true;
return reject();
});
ws.on('close',()=>{
if(!errorDetected){
resolve(); // -> need to wait for large files...
} // Else reject has already occured...
});
rs.pipe(ws);
} else reject();
})
}
async function mergeFiles(dest, files){
for(var i=0;i<files.length;i++){
let w=fs.createWriteStream(dest,{flags: 'a', encoding: 'utf-8'});
let r=fs.createReadStream(files[i]);
await copyFileContent(w,r);
}
}
After some investigation, I have doublechecked that the close event on the writeStream (ws) was not a consequence of an error (which could justify that the content is truncated).
I finally added some delay by replacing the 'resolve()' statement by setTimeout(()=>{resolve()},3000);
And obviously allowing more time for the system (OS=Windows 10) to indeed write to file fixes the issue. But I don't understand why ! What is happening under the scene ? How to avoid such behaviour. I need to make sure that when the 'close' event occurs, then the file is indeed fully populated.
Can anyone help me finding my bug or misunderstanding on streams ?
Thx
I cannot get nockBack to record any fixtures, although it should do that. My test code looks as follows:
describe("#searchForProjects", function () {
beforeEach(function () {
nock.back.setMode("record");
this.con = getTestConnection(ApiType.Production);
});
it("finds a home project", async function () {
const { nockDone, context } = await nock.back("search_for_project.json");
await searchForProjects(this.con, "home:dancermak", {
idOnly: true,
exactMatch: true
}).should.eventually.deep.equal([
{
name: "home:dancermak",
apiUrl: normalizeUrl(ApiType.Production)
}
]);
nockDone();
});
});
Just running this specific test results in a NetConnectNotAllowedError: Nock: Disallowed net connect for $URL.
I have tried including a nock.restore() before the whole test, which results in the request going through, but nock doesn't bother recording anything.
The underlying code is using the https module from nodejs, so that shouldn't be a problem?
Any help would be greatly appreciated.
I have finally managed to crack this and the solution is embarrassingly simple: recording must be activated before creating any http(s).request calls. In my case it was obscured a bit as I have a class that on construction saves either http.request or https.request in a member variable. Activating the recorder beforehands solves the issue.
For me the problem was that I had a failing assertion in my test. This meant that nockDone was not called and so no nocks were written to disk.
I am using firebase functions Database Triggers.
My Function :
exports.function_name = functions.database
.ref("/transact/{entry_type}/{id1}/{id2}/trigger_cross_entry_function")
.onCreate((data, context) => {
console.log("trigger_cross_entry_function value", data.val());
if (data.val() == true) {
console.log("Function Calling parent data");
return data.ref.parent.once('value').then(function(snapshot){
}, function(error) {
// The Promise was rejected.
console.error("THIS IS THE ERROR:"+error);
});
} else {
console.log("Function Returned");
return 0;
}
});
Whenever I want to trigger this function I put trigger_cross_entry_function into that partcular path from the Mobile App. Everything works fine and function is called as expected.
After sometime If I again try to do the same thing it gives me
Function execution took 16 ms, finished with status: 'connection error'
If I restart the function than it again works perfectly.
and If I trigger it continously than it has no issue.
But once I keep it idle and try to trigger it
again after sometime, it gives me this error.
And I am using Firebase Pay as you go Plan.
Also, as you can see I am returning all the promises correctly and function is being triggered everytime but It doesnt go into the function. it just exit with connection error.
What might be the cause for this ? I have a spent a day finding this.
Experiencing the same issue. Looks like Google changed the status of the service to down
https://status.firebase.google.com/incident/Functions/18046
https://status.firebase.google.com/
So most likely the Google side problem.
So I have been building a cli/gui app using electron for work. I have a progress bar that needs an interval to be run every so often to refresh the progress bar. Recently we wanted to run this in jenkins so having progress bars refresh ever 80 ms would be super anoying. I added some code to clear the interval if a certain environment variable was set and then for some reason the app started to hang after sending http requests. The server would never receive the requests and the app would just sit there. After a lot of debugging i have found that putting a setInterval(() => { }, 80); (one that does anything or nothing for any amount of time) anywhere in the code fixes the problem. Has anyone seen this before? i feel like I'm going crazy!
edit:
setting a timeout on the request will make the request fail after the timeout.
edit:
so I can't show you the exact code but here is the jist of one of the request calls.
return new Promise((resolve, reject) => {
request.put({
url: this.buildUrl(armada, '/some-path'),
body: vars,
json: true
}, (err, resp, body) => {
logger.comment('err "%s"', JSON.stringify(err));
logger.comment('resp "%s"', JSON.stringify(resp));
logger.comment('body "%s"', JSON.stringify(body));
let e = this.handleError(err, resp, body, 'Error getting stuff');
if (e) { return reject(e); }
logger.comment('got back body "%s"', body);
resolve(resp);
});
});
and then if I have an interval somewhere it doesn't hang. and if I don't it does.
i can paste this code anywhere in my code and everything starts working
setInterval(() => { }, 80);
Now it's not a specific request made as the app makes a lot of different requests. any of the requests it makes can hang. And they don't always hang. about 1 in 10 times everything will work just fine for an individual request.