Reputation: 55
I use dojo in Javascript and write a global function that has async function inside its. I want to call these function twice in a row ,but I want the first call finish before call the second.
I don't have source code right now but the structure is look like these.
initDataStore("store1");
initDataStore("store2");
initDataStore : function(storeName){
var request = openDB(storeName);
request.onUpgradeneed(function(){
//set some global value without return value
});
request.onSuccess(function(){
//set some global value without return value
});
}
I just try to use promise like these but I not sure if its work or not.
var p = Promise.resolve(initDataStore("store1"));
p.then(function(){initDataStore("store2")});
initDataStore : function(storeName){
var request = openDB(storeName);
request.onUpgradeneed(function(){
//set some global value without return value
return new Promise(function (resolve, reject){resolve("success"});
});
request.onSuccess(function(){
//set some global value without return value
return new Promise(function (resolve, reject){resolve("success"});
});
}
How to reslove these problem in the correct way?
PS. I don't want any return value ,I just want initDataStore("store2") to call after onUpgradeneed or onSuccess of initDataStore("store1") finish.
Upvotes: 3
Views: 3335
Reputation: 204
Nope, it won't work. You actually let the upgradeneed and success event function return a promise, but you actually don't let initDataStore return any thing...
Promises work this way :
function init(someParam){
return new Promise(function(resolve, reject){
// do something here
// and call either resolve(someValue) or reject(someValue)
});
}
init("aaa").then(function(val){/*success*/}, function(err){/*error*/});
Which should give us following:
function initDataStore(storeName){
return new Promise(function(resolve, reject){
var request = openDB(storeName);
request.onUpgradeneed(function(){
reject("Upgrade needed !");
});
request.onSuccess(function(){
resolve("OK !");
});
});
}
initDataStore("store1").then(function(val){
// val contains "OK !"
initDataStore("store2").catch(function(err){/*second one did not work*/});
}, function(err){
// first one did not work
// err contains "Upgrade needed !"
});
Upvotes: 2