JS 从带有 Promise 的构造函数中获取数据



我无法从 GetPhoto 构造函数中的 unsplashAxios 获得数据响应,目前它只说"Promise { }"。我是否错过了一些显而易见的东西,或者这需要重新考虑?

尝试 1

class Unsplash {
constructor(path) {
return new Promise((resolve, reject) => {
unsplashAxios(path)
.then(response => {
resolve(response);
})
.catch(error => {
reject(error);
});
});
}
}
class GetPhoto {
constructor() {
console.log('Get Photo');
const unsplash = new Unsplash('/photos/PgHc0Ka1E0A');
console.log(unsplash)
// Console.log Response - Promise { <pending> }
}
}

尝试 2

class Unsplash {
constructor(path) {
return unsplashAxios(path)
}
}
class GetPhoto {
constructor() {
const unsplash = new Unsplash('/photos/PgHc0Ka1E0A');
unsplash.then((response) => {
console.log(response)
}).catch((response) => {
console.log(response);
});
}
}

尝试 3 - @Klaycon后,我重写了上述内容,这似乎有效。但是反馈会很棒(好或坏(。

const unsplashAxios = require('./unsplashAxios');
// Class
class Unsplash {
// Constructor
constructor() {
this.unsplash = null;
}
// Method
getPhoto(id){
this.unsplash = unsplashAxios( `/photos/${id}`);
this.unsplash.then((response) => {
console.log(response)
}).catch((response) => {
console.log(response);
});
}
// Method
getCollection(id){
this.unsplash = unsplashAxios(`/collections/${id}/photos`);
this.unsplash.then((response) => {
console.log(response)
}).catch((response) => {
console.log(response);
});
}
}
// Instance
myUnsplash = new Unsplash();
// Method
myUnsplash.getPhoto('PgHc0Ka1E0A');
// Method
myUnsplash.getCollection('62890');

你返回一个承诺。 正如@Bergi在您的评论中所说,避免在构造函数中使用它们。

用:

unsplash.then((data) => { 
//do something with data
});

等到承诺解决。你可以在这里阅读更多关于承诺的信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

由于unsplashAxios已经返回了一个承诺,因此您无需将其包装在另一个承诺中(您正在解析unsplashAxios的承诺,然后将该结果放入另一个必须在其他地方解决的承诺中。将您的代码更改为以下内容应该有效:

constructor(path) {
unsplashAxios(path)
.then(response => {
//do something with the response
})
.catch(error => {
//do something with the error
}
}
}

我最终重写并发现以下内容按预期工作:

class Unsplash {
constructor(path) {
return unsplashAxios(path)
}
}
class GetPhoto {
constructor() {
const unsplash = new Unsplash('/photos/PgHc0Ka1E0A');
unsplash.then((response) => {
console.log(response)
}).catch((response) => {
console.log(response);
});
}
}

最新更新