this method cant delete what is its error - vue.js

async onDeleteProduct(id, index){
try{
const result = await this.$axios.$delete('http://localhost:8000/api/products'+id)
if(result.status){
this.products.splice(index, 1)
}
} catch(err){
console.log(err)
}
},

Related

Error loading preview in Firebase Storage

This is my function put
var metadata = {
contentType: 'image/png'
}
const task = fireStore.ref(fileName).put(uploadUri, metadata)
try {
await task
setUpLoading(false)
} catch(err) {
console.log(err)
}
but it didn't work.
Thanks for help.
I found solution for it.
let newImageUri
try {
const response = await fetch(imageUrl)
const blob = await response.blob()
await firebase.storage().ref().child(fileName).put(blob)
var ref = firebase.storage().ref().child(fileName).put(blob)
newImageUri = await ref.snapshot.ref.getDownloadURL()
} catch (error) {
console.log(error)
}

I am getting `Can not use keyword 'await' outside of a async function` within an Async function.. React-native

I am having an issue with async await for my AsyncStorage function within my React-native application. The error I'm getting is:
Can not use keyword 'await' outside of a async function
As you can see below, it's obvious that await is within the function. What am I doing wrong to get this error?
_retrieveData = async function (location) {
try {
var index = await AsyncStorage.getItem(location, (err, result) => result).then(result => result).catch(error=>console.log(error))
if (index !== null) {
return JSON.parse(index)
}
} catch (error) {
return null
}
};
_storeData = async function(location, value) {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error)
}
};
Use ES6 arrow functions
const _retrieveData = async location => {
try {
let index = await AsyncStorage.getItem(location)
if (index !== null) {
return JSON.parse(index);
}
} catch (error) {
return null;
}
};
const _storeData = async (location, value) => {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};
Make them as an arrow functions
_retrieveData = async location => {
try {
let index = await AsyncStorage.getItem(location)
if (index !== null) {
return JSON.parse(index);
}
} catch (error) {
return null;
}
};
_storeData = async (location, value) => {
try {
await AsyncStorage.set(location, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};

React Native, fetch after async function

I have a problem that I do not know how to solve...
I have an api token saved in AsyncStorage, and when I want do fetch to rest I need this api token, but I do not know how to do it.
I have file Functions.js with AsyncStorage functions.
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.warn(error.message);
}
},
getApiToken: function(){
try {
return Functions.retrieveItem('api_token');
} catch (error) {
console.warn(error.message);
}
},
File with fetch functions. (Api.js)
I tested with an asynchronous function, but not found...
async get(url) {
try {
var api = await Functions.getApiToken();
if (!api)
api = "";
let opt = {
method: 'get',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
}),
};
return fetch(baseUrl + url + api, opt);
} catch (error){
console.warn(error);
}
},
When I did the fetch function, it worked for me without problems
And the screen file Home.js
componentDidMount() {
Api.get('home').then( response => {
this.setState({
profiles: response.profiles,
});
});
}
Please modify your Functions.js code a bit -
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.warn(error.message);
}
},
async getApiToken{
try {
let token = await retrieveItem('api_token');
return token;
} catch (error) {
console.warn(error.message);
}
}
Hope this helps you!

passing Tedious connection as parameter

I am trying to use a simple suite of functions built utilizing the Tedious library to access a Microsoft SQL Server. Here is my "tools" file:
'use strict';
const tedious = require('tedious');
const q = require('q');
var Connection = tedious.Connection;
var Request = tedious.Request;
module.exports = {
connectSQL : function(config) {
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log('FAIL ON CONNECT');
console.log(err);
} else {
try {
/* ----- */
return connection;
} catch (err) {
console.log(err);
return;
}
}
});
connection.on('error', function(err) {
if (err) {
console.log('FAIL ON ERROR');
console.log(err);
} else {
console.log("Error called with no err object.");
}
});
},
executeSQL: function(connection, requestString) {
var results = [];
var request = new Request( requestString , function(err, data) {
if (err) {
console.log(err);
} else {
console.log( data );
}
});
request.on('row', function(row) {
//console.log(row);
results.push( row );
});
request.on('requestCompleted', function(){
console.log('Finished');
return results;
});
connection.execSql(request);
}
}
I call these functions as follows in my server file.
const sqlTools = require('./sqlTools.js');
var connection = sqlTools.connectSQL(config);
sqlTools.executeSQL(connection, "select * from dbo.test");
However, I get the error "TypeError: Cannot read property 'execSql' of undefined", even if I make the program sleep for 10 seconds before calling my function sqlTools.executeSQL (obviously not ideal).
I was able to get this to work by calling the request within the sqlTools.connectSQL function (at the "/* ----- */"), but I want to re-use the Tedious connection to make multiple calls. Any suggestions? Thanks!
~~~~~~~EDIT~~~~~~~~~~
With help from akinjide I was able to implement callbacks that allow me to make a single call to my SQL database. However, I am struggling to implement promises to make subsequent calls. I changed my "tools" file as such:
'use strict';
const tedious = require('tedious');
const q = require('q');
var Connection = tedious.Connection;
var Request = tedious.Request;
module.exports = {
connectSQL: function(config) {
var deferred = q.defer();
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
deferred.reject( err );
} else {
deferred.resolve( connection );
}
});
connection.on('error', function(err) {
deferred.reject(err);
});
return deferred.promise;
},
executeSQL: function(connection, requestString, callback) {
var results = [];
const request = new Request(requestString, function(err) {
callback(err);
});
request.on('row', function(row) {
results.push(row);
});
request.on('requestCompleted', function() {
console.log('request completed!');
callback(null, results);
});
connection.execSql(request);
}
}
and I call this code like this...
var promise = sqlTools.connectSQL(config);
promise.then(function (connection) {
sqlTools.executeSQL(connection, "select * from dbo.test", function(err, results) {
if (err) {
console.log(err);
}
console.log(results);
});
}).catch(function (err) {
console.log(err);
}).then(function (connection) {
sqlTools.executeSQL(connection, "select * from dbo.test2", function(err, results) {
if (err) {
console.log(err);
}
console.log(results);
});
}).catch(function(err) {
console.log(err);
});
This returns the first call's results correctly, but unfortunately returns this error "TypeError: Cannot read property 'execSql' of undefined" for the second call as it is not recognizing the connection the second time around. Any suggestions?
A better approach would be to pass a node.js callback style function as an argument to connectSQL.
return keyword won't work within an asynchronous program.
'use strict';
const tedious = require('tedious');
const Connection = tedious.Connection;
const Request = tedious.Request;
module.exports = {
connectSQL: function(config, callback) {
const connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
callback(err);
} else {
callback(null, connection);
}
});
connection.on('error', function (err) {
callback(err);
});
},
executeSQL: function(connection, requestString, callback) {
let results = [];
const request = new Request(requestString, function(err) {
callback(err);
});
request.on('row', function(row) {
results.push(row);
});
request.on('requestCompleted', function(){
console.log('Finished');
callback(null, results);
});
connection.execSql(request);
}
}
Then you can require, use sqlTools.connectSQL passing two parameters config and function(err, connection) {}
const sqlTools = require('./sqlTools');
sqlTools.connectSQL(config, function(err, connection) {
if (err) {
console.log('FAIL ON CONNECT');
console.log(err);
}
sqlTools.executeSQL(connection, "select * from dbo.test", function (err, results) {
if (err) {
console.log(err);
}
console.log(results);
});
});

Using async / await with mongoose.js

Looking for help to rewrite these 2 queries using async / await instead of using the nested callbacks approach.
exports.post_edit_get = function(req, res, next) {
var id = req.params.id;
if (mongoose.Types.ObjectId.isValid(id)){
POST.findById(id, function (err, doc){
if (err) { return next(err); }
playerQuery.exec(function (err, players){
if (err) { return next(err); }
res.render('posts/posts_admin', { title: pageTitle, formData: doc, players: players });
});
});
}else{
res.send("Invalid ID");
};
};
Here you go
const { isValid } = mongoose.Types.ObjectId
exports.post_edit_get = async function(req, res, next) {
var { id } = req.params;
if (!isValid(id)){
return res.send("Invalid ID");
}
try {
const post = await POST.findById(id)
const players = await playerQuery.exec()
res.render('posts/posts_admin', {
title: pageTitle,
formData: doc,
players: players
})
} catch (err) {
return next(err)
}
}
If you want to get rid of these try/catches at the route handler level you'll want to have a look at this post; Using async/await to write cleaner route handlers