AsyncStorage和Promise配合使用
阿新 • • 發佈:2018-12-28
程式碼:
AsyncStorage封裝
import {AsyncStorage} from "react-native"; class DeviceStorage { //儲存資料 static saveData(keyName,keyValue) { var p = new Promise(function(resolve, reject){ //做一些非同步操作 AsyncStorage.setItem(keyName, keyValue, function (error) { if (error) { return resolve('儲存失敗'); } else { return resolve('儲存成功'); } }) }); return p; } static loadData(keyName) { var p = new Promise(function(resolve, reject){ //做一些非同步操作 AsyncStorage.getItem(keyName, function (error, result) { if (!error) { return resolve(result); }else{ return resolve( '資料已經刪除') } }) }); return p; } //刪除指定的資料 static delData(keyName) { var p = new Promise(function (resolve,reject) { AsyncStorage.removeItem(keyName, function (error) { if (!error) { return resolve( '資料已經刪除') ; }else{ return resolve('資料刪除失敗' ); } }) }) return p; } } export default DeviceStorage;
使用:
//儲存 DeviceStorage.saveData("name","lpp").then(function(data){ alert(data) }); //獲取 DeviceStorage.loadData("name").then(function(data){ alert(data) }); //刪除 DeviceStorage.delData("name").then(function(data){ alert(data) });