繁体   English   中英

JavaScript函数(callback).then(),然后执行回调

[英]JavaScript function(callback).then(), callback executes after then

我很难让它工作。

我有一个功能getItem

export const getItem = async (key, callback) => {
    value = await Expo.SecureStore.getItemAsync(key).catch((error) => console.log(error));
    callback(value);
}

假定使用getItem获取令牌并将该令牌传递给回调。

现在,我想在这个(简化的)类中使用getItem

export class Post {
    constructor(){
        this.token = false;
    }

    post() {
        console.log('Token: ' + this.token);
        ...
    }

    setToken(token){
        console.log('Set token.');
        this.token = token;
    }

    authorizedPost() {
        getItem('token', this.setToken.bind(this)).then(
            this.post()
        );
    }
}

我像这样使用此类:

let post = new Post();
post.authorizedPost();

这是我得到的输出:

Token: false
Set token.

但是我需要设置令牌,然后,我要调用方法this.post()

由于我是一个初学者,所以我想原谅一下这个问题。 但是我很感谢你的帮助!

我必须传递一个函数,然后这样:

authorizedPost() {
        getItem('token', this.setToken.bind(this)).then(
            ()=>this.post()
        );
    }

我知道您并没有真正问过,但是…

代码难于调试的部分原因是因为您在不需要时使用了回调并将它们与promise混合在一起。 这是两个不同的异步范例,通常最好分开放置。 您可以在一个方式,这将使它更具可读性在您的代码摆脱回调。

 Expo.SecureStore.getItemAsync()

返回诺言,所以就兑现它。

const getItem = (key) => Expo.SecureStore.getItemAsync(key);

然后,在您的方法中,您可以调用then并简单地调用您作为回调传递的函数。 无需回调或绑定。 在另一行之后:

authorizedPost() {
  getItem('token').then(val => {
    this.setToken(val)           // the order is now obvious
    this.post()
  })
  .catch((error) => console.log(error))
}

这是一个伪造的Expo方法的代码段:

 let Expo = { SecureStore: { getItemAsync() { return new Promise((resolve, reject) => setTimeout(() => resolve("someFancyToken"), 1000)) } } } class Post { constructor() { this.token = false; } post() { console.log('Token: ' + this.token); } setToken(token) { console.log('Set token.'); this.token = token; } authorizedPost() { getItem('token').then(val => { this.setToken(val) this.post() }) .catch((error) => console.log(error)) } } const getItem = (key) => Expo.SecureStore.getItemAsync(key); let post = new Post(); post.authorizedPost(); 

暂无
暂无

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

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