简体   繁体   English

如何履行承诺

[英]How to handle promises

I am having an issue with Promises, I have writted a function which tries to get data from Shared preferences and once I receive it, I return a Promise . 我在Promises方面遇到问题,我编写了一个函数,该函数尝试从Shared首选项中获取数据,一旦收到,便返回Promise In the function I am using it returns Unhandled promise rejection cannot read the property then of undefined 在我正在使用的函数中,返回Unhandled promise rejection cannot read the property then of undefined

Here is my function which gets the data from shared preferences and returns a promise 这是我的函数,该函数从共享的首选项中获取数据并返回承诺

  export function isMock(){
    const returned = getSharedPreferenceValue( Globals.SHARED_PREFERENCES_KEY_IS_TEST_USER).then ((isTestUser) => {  
        consoleLog('isMock - ' + isTestUser);//THIS LINE WORKS 
        return Promise.resolve(isTestUser === 'true' ? true : false);
      })
      .catch(err => {
        consoleLog('error -' + err);
        return {error:err, response: null};
      });
}

Here is the function where I am trying to use the above function. 这是我尝试使用上述功能的功能。

export function login ( abcd, xyz ){

    const returned = isMock().then((isMock) => {
        //Do some based on isMock.
        console.log(`Login isMock - ` + isMock); //DOES NOT PRINT
    })
    .catch(error => {
          console.log('Login isMock - error - ' + JSON.stringify(error));
      });
}

Here is the error message 这是错误消息

Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot read property 'then' of undefined
TypeError: Cannot read property 'then' of undefined

Could you please suggest where I am going wrong. 您能否建议我要去哪里错了。

Update 更新资料

After following the answer creating New promise resolved the issue in that function but the error was coming from another one. 按照答案创建新承诺后,该函数中的问题解决了,但错误来自另一个。

function inMock which is now fixed inMock功能现已修复

export function isMock(){
    return new Promise((resolve, reject) => {
        getSharedPreferenceValue(Globals.SHARED_PREFERENCES_KEY_IS_TEST_USER).then(isTestUser => {
          consoleLog('isMock - ' + isTestUser);
          resolve(isTestUser === 'true' ? true : false);
        }).catch(err => {
          consoleLog('error -' + err);
          reject(err)
        });
      });
}

isMock is called here and issue is in else statement which returns a promise isMock在这里被调用,问题在else语句中,该语句返回一个promise

export function login ( ABCD, XYZ ){
    const returned = isMock().then((isMock) => {
        consoleLog('login Legacy API - isMock() - ' + isMock);//THIS WORKS
        if(!isMock){
            console.log('isMock is false');
        }else{

            consoleLog('mock data - ../mockData/login.json');
            var user = require('../mockData/login.json');//WORKS

            return Promise.resolve(user);//PROBLEM MIGHT BE HERE
        }
    })
    .catch(error => {
          console.log('Login isMock - error - ' + JSON.stringify(error));
      });
}

Main calling function of Login is here which gives me the error 登录的主要调用功能在这里,这给了我错误

loginUser_legacy = async (ABCD, XYZ) => {  
    const returned = await login(cardDigits, nationalIdNumber).then((res) => {
      consoleLog('res - ' + res);//DOES NOT WORK
    });

  }

Thanks R 谢谢R

I think, are you not returning returned in isMock() ? 我认为,您是否不返回isMock() returned isMock()

So although in the catch you return {error:err, response: null} , you never actually get an error as you are return Promise.resolve(isTestUser === 'true' ? true : false); 因此,尽管在catch您返回{error:err, response: null} ,但实际上在return Promise.resolve(isTestUser === 'true' ? true : false); ,您从未真正得到错误return Promise.resolve(isTestUser === 'true' ? true : false); which always returns a resolved (albeit resolved with a true or false ) and thus never goes into the catch (which is also async so isn't aaccctually returned) 它总是返回一个resolved (尽管使用truefalse解析),因此永远不会陷入陷阱(这也是异步的,因此不会被准确地返回)

edit, possible what to do: 编辑,可能做什么:

export function isMock(){
  return new Promise((res,rej)=> {
   getSharedPreferenceValue(Globals.SHARED_PREFERENCES_KEY_IS_TEST_USER).then ((isTestUser) => {  
    res(isTestUser === 'true')
  }).catch(rej)
 }

} }

A new promise is returned; 返回了新的承诺; this will getSharedPreferenceValue , if this succeeds then resolve the new promise with your answer. 这将是getSharedPreferenceValue ,如果成功,则用您的答案解决新的承诺。 If this fails, pass the error into the reject function which will also pass back to the isMock() caller which will catch it. 如果失败,则将错误传递到拒绝函数,该函数还将传递回isMock()调用程序,该调用程序将捕获该错误。

看起来函数应该是getSharedPreferences()而不是getSharedPreferencesValue()

you don't have to use Promise.resolve since getSharedPreferenceValue itself is a promise... you could try to return just the values.... 您不必使用Promise.resolve,因为getSharedPreferenceValue本身是一个承诺...您可以尝试仅返回值...。

also you should not resolve a promise inside a thenable function as per documentation 而且你不应该按照文档在一个可行的函数中解决一个承诺

you could try this way or you could simply use async/await 您可以尝试这种方式,也可以只使用async / await

export function isMock(){
const returned = getSharedPreferenceValue( Globals.SHARED_PREFERENCES_KEY_IS_TEST_USER).then ((isTestUser) => {  
    consoleLog('isMock - ' + isTestUser);//THIS LINE WORKS 
    return isTestUser === 'true' ? true : false;
  })
  .catch(err => {
    consoleLog('error -' + err);
    return {error:err, response: null};
  });

} }

Try returning a new Promise. 尝试返回一个新的Promise。

 export function isMock() { return new Promise((resolve, reject) => { getSharedPreferenceValue(Globals.SHARED_PREFERENCES_KEY_IS_TEST_USER).then(isTestUser => { consoleLog('isMock - ' + isTestUser); resolve(isTestUser === 'true' ? true : false) }).catch(err => { consoleLog('error -' + err); reject(err) }) }) } 

-- Update -- -更新-

Promise.resolve(user) will return promise for this scope only which is isMock(). Promise.resolve(user)仅针对此范围isMock()返回Promise。

 export function login ( ABCD, XYZ ){ const returned = isMock().then((isMock) => { consoleLog('login Legacy API - isMock() - ' + isMock); if(!isMock){ console.log('isMock is false'); }else{ consoleLog('mock data - ../mockData/login.json'); var user = require('../mockData/login.json'); return Promise.resolve(user); // This line will return Promise for this scope only (isMock function) } }) .catch(error => { console.log('Login isMock - error - ' + JSON.stringify(error)); }); } 

So to fix this, return a new Promise. 因此,要解决此问题,请返回一个新的Promise。

 export function login(ABCD, XYZ) { return new Promise((resolve, reject) => { isMock() .then((isMock) => { consoleLog(`login Legacy API - isMock() - ${isMock}`); if (!isMock) { consoleLog('isMock is false'); } else { consoleLog('mock data - ../mockData/login.json'); const user = require('../mockData/login.json'); resolve(user); } }) .catch((error) => { consoleLog(`Login isMock - error - ${JSON.stringify(error)}`); reject(error); }); }); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM