[英]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.