你似乎混合了不同 Promise API 的 API。我没有看到你Promise
从任何地方进口。我想你正在使用内置的 JavaScript Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
使用 时Promise.all
,必须将其与 , 链接起来then
,而不是使用return
as next 语句。then
与解析器/拒绝链接。
您的代码return
在之后使用 so ,Promise.all
但您没有调用then
,因此它会立即返回并且索引尚未准备好创建。
此代码有效:
import r from 'rethinkdb';
import config from '../config';
const createDatabase = (conn, name) =>
r.dbList().contains(name)
.do(containsDb =>
r.branch(
containsDb,
{ created: 0 },
r.dbCreate(name)
)
)
.run(conn)
.error(err => {
console.log(`Could not create ${name} DB`);
console.log(err.message || 'Something bad happened');
process.exit(1);
});
const createTable = (conn, name) =>
r.tableList().contains(name)
.do(containsTable =>
r.branch(
containsTable,
{ created: 0 },
r.tableCreate(name)
)
)
.run(conn)
.error(err => {
console.log(`Could not create ${name} table`);
console.log(err.message || 'Somthing bad happened');
process.exit(1);
});
const createIndex = (conn, tableName, indexName) =>
r.table(tableName).indexList().contains(indexName)
.do(containsIndex =>
r.branch(
containsIndex,
{ created: 0 },
r.table(tableName).indexCreate(indexName)
)
)
.run(conn)
.error(err => {
console.log(`Could not crate index ${indexName} in ${tableName}`);
console.log(err.message || 'Something bad happened');
process.exit(1);
});
const waitForIndex = (conn, tableName, indexName) =>
r.table(tableName).indexWait(indexName)
.run(conn)
.error(err => {
console.log('Something bad happened while waiting for index created');
console.log(err.message || 'Something bad happened');
process.exit(1);
});
export const setup = startApp => {
r.connect(config.rethinkdb)
.then(conn => {
createDatabase(conn, 'test');
return conn;
})
.then(conn => {
return Promise.all([
createTable(conn, 'todos'),
createTable(conn, 'days'),
]).then((result) => conn, (reason) => conn)
})
.then(conn => {
return Promise.all([
createIndex(conn, 'todos', 'createdAt'),
createIndex(conn, 'days', 'date'),
]).then(() => conn, () => conn)
})
.then(conn => {
return Promise.all([
waitForIndex(conn, 'todos', 'createdAt'),
waitForIndex(conn, 'days', 'date'),
])
}
)
.then(() => {
console.log('DB and tables are available, starting Koa ...');
startApp();
})
.error(err => {
console.log('Could not open a connection to initiailize the database');
console.log(err.message || 'Something bad happened');
process.exit(1);
});
};
setup()
请注意,我们必须使用then
传递conn
对象,而不是通过返回