This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 months ago.
I want to get a value from chrome.storage.local
var storage = chrome.storage.local;
authToken = storage.get('logintoken', function(result) {
var channels = result.logintoken;
authToken=result.logintoken;
console.log(authToken);
return authToken;
});
alert(authToken);
but out of the function authToken is undefined.
function getAllStorageSyncData(top_key) {
// Immediately return a promise and start asynchronous work
return new Promise((resolve, reject) => {
// Asynchronously fetch all data from storage.sync.
chrome.storage.local.get(top_key, (items) => {
// Pass any observed errors down the promise chain.
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
// Pass the data retrieved from storage down the promise chain.
resolve(items);
});
});
}
Used this method and await like
var obj = await getAllStorageSyncData(['logintoken']);
and its worked
https://stackoverflow.com/a/72947864/1615818
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How can I access the value of a promise?
(14 answers)
Closed 7 months ago.
I found that it's not straight forward to filter a list of values of promises, so I tried the approach in this question (top answer).
The difference is, i'm using this inside useEffect in React.
My results array is empty outside of the async getData function:
// helper function
async function filter(arr, callback) {
const fail = Symbol();
return (
await Promise.all(arr.map(async (item) => ((await callback(item)) ? item : fail)))
).filter((i) => i !== fail);
}
useEffect(() => {
if (!stateData) {
let results = [];
async function getData() {
const res = await filter(data.slice(0, 5), async (item) => {
const boolRes = await myAsyncFunction(item);
return boolRes;
});
// results has data
results.push(...res);
}
getData();
console.log(results) // is empty, but results inside getData has data
}
}, []);
any idea how I can pull the data out of getData safely?
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I make calendar for my project and need to use seved data from server inside "function CalendarPicker()".
I get data from server as promise and try use it inside "function CalendarPicker()" but always get undefined. How can I force it?
async function _getMeetingsData() {
let response = await fetch('calendar');
let data = await response.json();
data = JSON.stringify(data);
return data;
}
function CalendarPicker() {
//Get meeting data
this.meetingsData = _getMeetingsData();
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
}
const myCalender = new CalendarPicker();
You need to have an async constructor (arguably odd) or await for your data, because every async function is implicitly a promise, even if it synchronously returns a value ... so:
function CalendarPicker() {
//Get meeting data ... then
_getMeetingsData().then(meetingsData => {
this.meetingsData = meetingsData;
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
});
}
This works, but if you have any prototype method that needs that data, you better store the promise:
function CalendarPicker() {
//Get meeting data ... then
this._meetingsData = _getMeetingsData().then(meetingsData => {
this.meetingsData = meetingsData;
this._insertNavigationButtons();
this._insertHeaderIntoCalendarWrapper();
this._insertCalendarGridDaysHeader();
this._insertDaysIntoGrid();
this._insertCalendarIntoWrapper();
});
}
CalendarPicker.prototype.doThings = function () {
this._meetingsData.then(() => {
console.log(this.meetingsData);
});
};
Because you have defined _getMeetingsData as an async function, you need to call _getMeetingsData with the await keyword. In that case, you also need to make CalendarPicker an async function. Alternatively, you can call _getMeetingsData within a promise construct in your CalendarPicker function.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return values from async functions using async-await from function? [duplicate]
(3 answers)
Closed 3 years ago.
I'm trying to load a CSV file into my application at the beginning and keep the value in a variable and call it from other functions instead of accessing by then all the time
my code is
var DVizModule = (() => {
let dataset = [];
let _data = async () => {
const data = await d3.csv("data/alphabet.csv");
return data;
}
let data = _data().then(data => {
dataset = data;
return dataset;
})
return {
data: data
}
})();
console.log(DVizModule.data);
it returns
Promise pending proto: Promise
PromiseStatus: "resolved"
PromiseValue: Array(26)
When I write
const t = async function() {
const data = await d3.csv("data/alphabet.csv");
return data;
}
t().then(result => console.log(result))
it returns the file perfectly
I'm trying to access the file content via
DVizModule.data
If you want to access data synchronously, you should declare it as a plain value, not a promise. something like this should do the trick:
const DVizModule = {};
d3.csv("data/alphabet.csv").then(data => DVizModule.data = data);
Note, of course, that DVizModule.data will be undefined until the request is actually complete. If you want to ensure that the value actually is there, you will have to wrap the outer context into an async function and await the data at the very beginning. This way you can both ensure that the value is present when you code accesses it and use it in a synchronous manner.
Hope I got your question right and not trying to resolve the wrong problem ;)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
Although I found similar questions to mine, I couldn't solve the problem on my own.
In my '../models/user' model I want to find all users and put them into array, and return that array to the controller(where I will use the info).
Here is my code:
var mongoDatabase = require('../db');
var database = mongoDatabase.getDb();
function find() {
var test;
database.collection("customers").find().toArray( function(err, docs) {
if(err) throw err;
console.log(docs); //works fine
//I'd like to return docs array to the caller
test = docs;
});
console.log(test); //test is undefined
}
module.exports = {
find
};
I also noticed, that 'console.log(test)' goes before 'console.log(docs)'. I tried passing 'docs' argument as function parameter to 'find', but without result.
The best way is to use Promises. Do it like this.
function getUsers () {
return new Promise(function(resolve, reject) {
database.collection("customers").find().toArray( function(err, docs) {
if (err) {
// Reject the Promise with an error
return reject(err)
}
// Resolve (or fulfill) the promise with data
return resolve(docs)
})
})
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I know you can access a Promise’s value inside the .then method like the following code:
const Promise = require("bluebird");
const fs = Promise.promisifyAll(require('fs'));
const mergeValues = require('./helper').mergeValues;
fs.readFileAsync('./index.html', {encoding: "utf8"})
.then((data) => {
return mergeValues(values, data); //async function that returns a promise
})
.then((data) => {
console.log(data);
});
In the above example, I’m reading from a file, merging the data with some values, and then logging the data to the console.
But how about returning the value from a function, as you normally would in a synchronous function? If I follow this comment on synchronous inspection, I think the code should look like this:
function getView(template, values) {
let file = fs.readFileAsync('./' + template, {encoding: "utf8"});
let modifiedFile = file.then((data) => {
return mergeValues(values, data);
});
return modifiedFile.then((data) => {
return modifiedFile.value();
});
}
console.log(getView('index.html', null));
But for some reason, it’s not working. All I’m getting in the console is the Promise object itself, not the value. And when I add the .isFulfilled method on modifiedFile, it outputs to true. So I’m not sure what I’m doing incorrectly.
Promises don't work that way. They are asynchronous by nature, so you can't interact with them in the same way you do with synchronous code.
That means you have to use the then method to get at the value:
function getView(template, values) {
let file = fs.readFileAsync('./' + template, {encoding: "utf8"});
let modifiedFile = file.then((data) => {
return mergeValues(values, data);
});
return modifiedFile.then((data) => {
return modifiedFile.value();
});
}
// This won't work
// console.log(getView('index.html', null));
// instead:
getView('index.html', null).then(function (view) {
console.log(view);
});
So I’m not sure what I’m doing incorrectly.
You're not doing anything incorrectly, actually. You just can't use promises like a normal return value from a function. Period.