我在一处地方要调用 logInWidthMobilePhone(),想要获取signUpOrlogInWithMobilePhone中的返回结果,但是logInWidthMobilePhone返回的始终是undefined:
export default{
logInWidthMobilePhone(phone, code) {
leanStorage.User.signUpOrlogInWithMobilePhone(phone, code).then((success) => {
// 成功
return success
}, (error) => {
// 失败
return error
});
}
}
请问我该怎么实现?
最直接的原因,
logInWidthMobilePhone
没有返回值,所以是undefined
。里面的两个return
语句都是写在箭头函数里的,所以是箭头函数的return
不是logInWidthMobilePhone
的。在异步函数调用完成之前你没法返回它的结果。所以对于异步函数,一般只有两种方案可选
返回 Promise
传入一个 callback 参数
当然我比较推荐返回 Promise 的方案
这样一来,其实不如就简单的返回
signUpOrlogInWithMobilePhone
的结果,即如果使用 ES7 语法,可以用 async/await 来处理简化外部的代码,具体参考“[从地狱到天堂,Node 回调向 async/await 转变](https://segmentfault.com/a/11...”
如果你想使用回调的方式,也差不多,就是给
logInWidthMobilePhone
多定义一个callback
参数,在里面return
的地方调用即可。