我正在尝试修复一些真正意义重大的代码,我试图解决的是删除新的Promise声明并返回初始的Promise,但我正在努力确保我正确地将之前和之后的tanslating。下面我有一个示例,概述了需要更改的场景之一。我错过了前后代码之间的某些内容,还是我正朝着正确的方向前进?另外,对于之后,我是否能够捕获所有被拒绝的错误?
在:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
app_name='shop'
urlpatterns = [
url('admin/', admin.site.urls),
url(r'^', include('shop.urls', namespace='shop')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
后:
add(book: IBook, authorId: string): Promise<IBookModel> {
let p = new Promise((reject, resolve) => {
let newBook: IBook = new Book({…book});
newBook.createInitialSetup();
let bookReady = {... newBook};
this.bookRepository.add(bookReady)
.then((completedBook: IBookModel) => {
this.bookRepository.findAuthorById(authorId)
.then((author: IAuthorModel) => {
let newBookAuthor: IAuthorModel = new Author();
newBookAuthor(completedBook._id, author._id);
let finalBookAuthor = {... newBookAuthor} as IAuthor;
this.bookRepository.addBookAuthor(finalBookAuthor)
.then((result: IBookAuthorModel) => {
resolve(completedBook);
})
.catch((err: Error) => {
reject(err);
});
})
.catch((err: Error) => {
reject(err);
});
})
.catch((err: Error) => {
reject(err);
});
});
return p;
}
答案 0 :(得分:3)
我错过了前后代码之间的某些内容,还是我正朝着正确的方向前进?
朝着正确的方向旅行。
也不要嵌套then
来电。链then:
add(book: IBook, authorId: string): Promise<IBookModel> {
let groupSetup: IGroupModel = new Group({...group});
newBook.createInitialSetup();
let bookReady = {... newBook};
return this.bookRepository
.add(bookReady)
.then((completedBook: IBookModel) => {
return this.bookRepository.findAuthorById(memberId)
})
.then(///so on
答案 1 :(得分:3)
num_classes = len(np.unique(y_train))
y_train_categorical = keras.utils.to_categorical(y_train, num_classes)
kf=StratifiedKFold(n_splits=5, shuffle=True, random_state=999)
# splitting data into different folds
for i, (train_index, val_index) in enumerate(kf.split(x_train, y_train_categorical)):
x_train_kf, x_val_kf = x_train[train_index], x_train[val_index]
y_train_kf, y_val_kf = y_train[train_index], y_train[val_index]
ValueError: Supported target types are: ('binary', 'multiclass'). Got 'multilabel-indicator' instead.
可能会让您的代码更易于理解和阅读:
Async/await
只是几个笔记:
async add(book: IBook, authorId: string): Promise<IBookModel> {
let newBook: IBook = new Book({ ...book });
newBook.createInitialSetup();
let bookReady = { ...newBook };
let completedBook: IBookModel = await this.bookRepository.add(bookReady)
let author: IAuthorModel = await this.bookRepository.findAuthorById(memberId)
let newBookAuthor: IAuthorModel = new Author();
newBookAuthor(completedBook._id, author._id);
let finalBookAuthor = { ...newBookAuthor } as IAuthor;
let result: IBookAuthorModel = await this.bookRepository.addBookAuthor(finalBookAuthor);
return completedBook
}
未在原始代码中定义memberId
代码覆盖整个代码,但由于您所做的只是转发错误,因此如果任何等待的承诺失败,则返回的try/catch
将被拒绝} LI>
Promise
的一般原则是有效的,但转换是在尖叫的婴儿背景下进行的,因此它可能有错误。