React Native中SecureStore getItemAsync返回Promise问题排查
问题分析与解决
代码与现象
我编写了如下Storage类:
//Fallback if SecureStore fails let data = {}; import * as SecureStore from 'expo-secure-store'; const Storage = { set: async function (key, value) { try { console.log("Setting Item"); console.log(key); console.log(value); return await SecureStore.setItemAsync(key, value); } catch (e) { //fallback if set cookie fails data[key] = value; } }, get: async function (key) { try { console.log("Gettimg Item"); console.log(key); let result = await SecureStore.getItemAsync(key); if (result) { return await result; } return null; } catch (e) { console.error(e); value = data[key]; return value; } } } export default Storage;
调用Storage.set的方式如下:
function() { Storage.set("some_key", "some_value"); }
控制台输出显示项已成功设置:
Setting Item user_id 4ce9dse7-650a-4ff5-955d-466a640de2c4 Setting Item user_first_name John Setting Item user_last_name Doe
但每次调用Storage.get(x)时,都会返回一个Promise:
Promise { "_A": null, "_x": 0, "_y": 0, "_z": null, }
明明在get方法里使用了两次await,为何仍返回Promise?问题出在哪里?
问题根源与解决方法
async函数的特性:所有被
async修饰的函数,无论内部是否使用await,返回值都会被自动包装成Promise对象。这是JavaScript异步函数的固有规则,和函数内部的await次数无关。调用时未解析Promise:你直接调用
Storage.get(x)却没有用await或.then()处理这个Promise,因此控制台只会输出Promise对象本身,而非实际存储的值。无效的多余await:
get方法里的return await result;完全没必要——result已经是await SecureStore.getItemAsync(key)的结果(字符串或null),对非Promise值使用await不会产生任何作用,可以直接写成return result;。
正确调用方式
要获取实际值,需在async函数内用await调用,或用.then()链式处理:
// 方式1:在async函数中使用await async function fetchData() { const value = await Storage.get("user_id"); console.log(value); // 输出实际存储的值 } // 方式2:用.then()链式调用 Storage.get("user_id").then(value => { console.log(value); // 输出实际存储的值 });
内容的提问来源于stack exchange,提问作者Devin Dixon
相关产品推荐
相关产品推荐

