使用await with react-native不起作用

时间:2018-01-11 12:44:40

标签: javascript react-native

我正在异步检索密码,这很正常:

static async login(){
let password = await User.getPassword();
alert(password); // this works, password is shown

但是如果我想在fetch中使用它,则无法正常工作

static async login(){
let password = await User.getPassword();
alert(password); // this works, password is shown
      return fetch(userInfoURL,
        { method: 'GET',
        headers: { 'Authorization':  password,
        'Content-Type': 'application/json'}
      })

服务器收到的密码为空

我也试过

User.getPassword().then((password) => {
return fetch(userInfoURL,
            { method: 'GET',
            headers: { 'Authorization':  password,
            'Content-Type': 'application/json'}
          })

但是我遇到了同样的问题,密码是空的。

2 个答案:

答案 0 :(得分:0)

你必须等待获取

return await fetch(userInfoURL,
   { method: 'GET',
    headers: { 'Authorization':  password,
   'Content-Type': 'application/json'}
})

答案 1 :(得分:0)

async getTabList(userId){
    try{
        let params = 'userId='+userId;

        let myR = await myRequest([yourURL],params);
        let response = await fetch(myR);
        let responseJson = await response.json();
        if(responseJson.code === 0){
            return responseJson;
        }else{
            Toast.fail('失败');
            return {};
        }
    } catch (error){
        Toast.fail('异常,请联系管理员');
    }
}

function myRequest(url,params){
    return new Request(url,{
        method:'POST',
        headers:{
            'Content-Type': 'application/x-www-form-urlencoded',
            // 加密
        },
        body:params,
    });
}