Reputation: 13
I am having trouble with the second function. It runs through before there is a value saved in 'w'. Ive tried setTimout() but it did not help. Im trying to implement async/await but im struggling with how it would fit with the code below:
function functionOne(){
var s
chrome.storage.local.get(['prm'], function(result) {
s = result.prm;
return s;
});
}
function functionTwo(){
let w = functionOne();
// second half runs after w is assigned a value (after functionOne is done running).
}
Is async/await the only solution or is there another way of solving it?
Upvotes: 1
Views: 142
Reputation: 35106
async / await is not the only solution. And in any case, you are going to need to create a promise in functionOne
/*async*/ function functionOne(){
var s;
var p = new Promise(function(success) {
chrome.storage.local.get(['prm'], function(result) {
s = result.prm;
success(s);
});
}
return p;
}
function functionTwo(){
let p = functionOne();
p.then(function(s) {
//...
});
}
You need to create a promise to be able to return the results of chrome.log.storage. You can make functionOne async or not. It doesn't change anything.
Upvotes: 1
Reputation: 451
You would have to use an asynchronous function that does not work all at once. You could do something like
function functionOne(){
var s
chrome.storage.local.get(['prm'], function(result) {
s = result.prm;
return s;
});
}
async function functionTwo(){
await let w = functionOne();
// second half runs after w is assigned a value (after functionOne is done running).
}
Referenced from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Note: I would also like to point out that functionOne actually returns an undefined value because inside the chrome.storage.local.get function the callback returns s, so you would need to move the return statement outside of the callback function.
Upvotes: 0