【发布时间】:2020-03-28 08:42:57
【问题描述】:
所以,我要在数据库中添加一个机构,然后在数据库中添加一个特殊的。一个机构可以有一对多特价,所以我试图在第三个.then() 下创建一个关系。问题是,然后第 3 个.then() 在建立之前执行,并将特殊添加到数据库中。我需要先将建立和特殊添加到数据库中,因为我需要获取它们的objectIds,var establishmentObjectId;和var specialObjectId;
如何确保在建立关系之前检索到建立和特殊 objectId?
//Save the establishment objectId
var establishmentObjectId;
//Save the special objectID
var specialObjectId;
//Save establishment
.then(() => {
//Get the add form data
var addName = document.getElementById('add_name');
var addCountry = document.getElementById('add_country');
var addEstablishmentType = document.getElementById('add_establishment_type');
var addCuisineType = document.getElementById('add_cusine_type');
//Create establishment from user's enteries
var establishment = {
Name: addName.value,
Address: addAddress.value,
Suburb: addSuburb.value,
Country: addCountry.value,
Cuisine_Type: addCuisineType.value,
Establishment_Type: addEstablishmentType.value
}
//Save establishment to db
Backendless.Data.of('Establishment').save( establishment )
.then( function( savedObject ) {
establishmentObjectId = savedObject.objectId;
console.log( "new Establishment instance has been saved" );
})
.catch( function( error ) {
console.log( "an error has occurred " + error.message );
});
})
//Save special
.then(() => {
//Get the add form data
var addCategory = document.getElementById('add_category');
var addTypeOfSpecial = document.getElementById('add_type_of_special');
var addDescription = document.getElementById('add_description');
//Create special from user's enteries
var special = {
Category: addCategory.value,
Type_Of_Special: addTypeOfSpecial.value,
Description: addDescription.value
}
//Save special to db
Backendless.Data.of('Special').save( special )
.then( function( savedObject ) {
specialObjectId = savedObject.objectId;
console.log( "new Special instance has been saved" );
})
.catch( function( error ) {
console.log( "an error has occurred " + error.message );
});
})
//Add special to establishment/form relation
.then(() => {
//These are undefined even though they are declared above
console.log(establishmentObjectId);
console.log(specialObjectId);
var parentObject = { objectId:establishmentObjectId };
var childObject = { objectId:specialObjectId };
var children = [ childObject ];
Backendless.Data.of( "Establishment" ).addRelation( parentObject, "establishmentSpecials", children )
.then( function( count ) {
console.log( "relation has been set" );
})
.catch( function( error ) {
console.log( "server reported an error - " + error.message );
});
})
非常感谢
【问题讨论】:
-
返回你要等待的promise,当它完成时,下一个
.then会被执行 -
创建promise链,然后返回promise。它会尝试解决它。
return Backendless.Data.of( "Establishment" )
标签: javascript promise backendless