f()函数中有个promise函数,f()函数如何返回promise中返回的结果?

我在一处地方要调用 logInWidthMobilePhone(),想要获取signUpOrlogInWithMobilePhone中的返回结果,但是logInWidthMobilePhone返回的始终是undefined:

export default{

    logInWidthMobilePhone(phone, code) {
            leanStorage.User.signUpOrlogInWithMobilePhone(phone, code).then((success) => {
                // 成功
                return success
            }, (error) => {
                // 失败
                return error
            });
    }

}

请问我该怎么实现?

阅读 6.5k
4 个回答

最直接的原因,logInWidthMobilePhone 没有返回值,所以是 undefined。里面的两个 return 语句都是写在箭头函数里的,所以是箭头函数的 return 不是 logInWidthMobilePhone 的。

在异步函数调用完成之前你没法返回它的结果。所以对于异步函数,一般只有两种方案可选

  1. 返回 Promise

  2. 传入一个 callback 参数

当然我比较推荐返回 Promise 的方案

export default {
    logInWidthMobilePhone(phone, code) {
        return new Promise((resove, reject) => {
            leanStorage.User.signUpOrlogInWithMobilePhone(phone, code)
                .then((success) => {
                    // 成功
                    resolve(success);
                }, (error) => {
                    // 失败
                    resolve(error);
                    // 实际上这里用 reject 比较好,但按你的逻辑应该用 resolve
                });
        });
    }
};

这样一来,其实不如就简单的返回 signUpOrlogInWithMobilePhone 的结果,即

export default {
    logInWidthMobilePhone(phone, code) {
        return new Promise((resove, reject) => {
            return leanStorage.User.signUpOrlogInWithMobilePhone(phone, code);
        });
    }
};

如果使用 ES7 语法,可以用 async/await 来处理简化外部的代码,具体参考“[从地狱到天堂,Node 回调向 async/await 转变](https://segmentfault.com/a/11...


如果你想使用回调的方式,也差不多,就是给 logInWidthMobilePhone 多定义一个 callback 参数,在里面 return 的地方调用即可。

里面的函数leanStorage 要使用return返回Promise, 而且这个函数本身也要使用return返回;这样logInWidthMobilePhone的结果也是一个Promise.

logInWidthMobilePhone(phone, code) {
    return leanStorage.User.signUpOrlogInWithMobilePhone(phone, code)
      .then((success) => {
         // 成功
         // 做点其它事情...on success
         return Promise.resolve(xxx)
      });
   }

return 一下试试

logInWidthMobilePhone(phone, code) {
  return leanStorage.User.signUpOrlogInWithMobilePhone(phone, code).then((success) => {
    return success
  }, (error) => {
    return error
  })
}
新手上路,请多包涵

不知道楼主有没有解决这个问题,我现在也有跟你一样的需求,折磨我好久了,有时候感觉.then(),真的有点多余。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题