【问题标题】:Is it logical to use async resolve ever?使用异步解析是否合乎逻辑?
【发布时间】:2018-09-16 18:28:44
【问题描述】:

我是 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 和类似的 Promises

return new Promise((resolve) => {
   AsyncStorage.getItem('some_val')
   .then((obj) => {
      // do stuff with obj
      resolve('yay')
   });

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

【问题讨论】:

  • 您根本不需要(手动创建的)承诺。就拿你的第一个例子来说,使函数异步,删除 new Promise 东西和 return 而不是 resolve
  • @tkausl 问题是如果我不返回任何东西,``` .then(() => { alert('loaded') });``` 即使没有完成代码也会完成在 someFunc 中(我正在用 fetch() 做一些请求)
  • 异步函数隐式返回一个承诺,该承诺将被解析为您返回的值。
  • 如果我不返回任何东西,它无论如何都会得到解决。那是我的问题。我想我不明白一些事情。顺便说一句,我在那个异步函数中也使用了 fetch 和 navigator.geolocation.getCurrentPosition
  • 好吧,这样说吧:如果您返回某些内容或函数以其他方式返回(在结束时}),它将得到解决,这与您遇到的行为相同您的示例 sn-ps。

标签: javascript react-native promise


【解决方案1】:

async 关键字添加到函数使其返回一个Promise。

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

你可以改写成:

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

    //do stuff with obj

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

【讨论】:

  • 问题是如果我不返回任何东西,``` .then(() => { alert('loaded') });``` 即使没有在@ 中完成代码,也会完成987654324@(我正在用fetch()做一些请求)
  • @good_evening — 我无法重现该问题:jsbin.com/lisivifeju/1/edit?js,console
  • 对不起,应该提到我在navigator.geolocation.getCurrentPosition 内部使用fetch()
  • @good_evening — 这是一个异步函数,所以你需要承诺 that
  • 你的意思是我需要将它包装在 Promise 类中?
【解决方案2】:

我只是通过删除不必要的东西来重构你的代码。

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);      
  }
}

【讨论】:

    猜你喜欢
    • 2018-10-31
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    相关资源
    最近更新 更多