使用异步解析是否合乎逻辑?

时间:2018-09-16 09:16:11

标签: javascript react-native promise

我是Promises的新手,所以我想知道这是否还可以:

this.someFunc()
  .then(() => {
    alert('loaded')
  });

someFunc() = () => {
  return new Promise(async(resolve) => {
    let obj = await AsyncStorage.getItem('some_val');

    //do stuff with obj

    resolve('yay, everything's done');
  });
};

或者我应该始终将then

这样的承诺一起使用
return new Promise((resolve) => {
   AsyncStorage.getItem('some_val')
   .then((obj) => {
      // do stuff with obj
      resolve('yay')
   });

?第一种方法是反模式吗?这是错的吗”?为什么呢?

2 个答案:

答案 0 :(得分:0)

在函数中添加async关键字使它返回Promise。

忽略那个诺言并将其包装在另一个诺言中并没有任何意义。它使代码使试图维护它的人感到困惑。

您可以将其重写为:

someFunc() = async () => {
    let obj = await AsyncStorage.getItem('some_val');

    //do stuff with obj

    return 'yay, everything's done';
};

答案 1 :(得分:0)

我只是通过删除不必要的内容来重构您的代码。

someFunc() = async () => { 
// when you declare arrow function, it should not have () with its name
// put async before arguments to enable await in the code block below 

 return new Promise(async(resolve) => { 
 // you don't need this line because of async and await
 // await returns data wrapped by Promise 
 // as soon as this Promise is resolved or rejected 

   let obj = await AsyncStorage.getItem('some_val'); 
   // 'await' will return the item that is wrapped by Promise. 
   // So, you can access the item(the returned data) in this code block. 
   // but if you want this 'someFunc' to return 'obj'

   //do stuff with obj

   resolve("yay, everything's done");
   // you don't need this line because 'await' will take care of
   // 'AsyncStorage.getItem('some_val')'
 });
};

重构后,您将获得如下代码。

someFunc = async () => { 
  // One of the benefit of async and await is that you can use try/catch block.
  // So, you can easily console out error without by chaining multiple '.catch' after 
  // every '.then'.
  try{
    let obj = await AsyncStorage.getItem('some_val');
    // 'obj' will be the value of item 'some_val'

    // do stuff with obj 
  } catch(error) {
    console.log(error);
  }
  return obj; //this will return resolved Promise because of await.
};

如果要在其他函数中使用此obj,则可以执行以下操作。

anotherFunc = async () => {
  try{
    const resolvedObj = await someFunc(); 
    // Since someFunc will return resolved Promise that wraps the data from
    // AsyncStorage, await will assign the data to 'resolvedObj'
    // However, if you return 'resolvedObj', this will be 'Promise {<resolved>: 
    // dataFromAsyncStorage}'

    // do stuff with 'resolvedObj'

  } catch(error) {
    console.log(error);      
  }
}