如何让 .then 在进入下一个之前完全完成?

How to make .then completely finish before moving onto the next?

因此,我正在向数据库中添加一个机构,然后向数据库中添加一个特价商品。一个机构可以有 1 到许多特价,所以我试图在第 3 个 .then() 下创建一个关系。事情是,然后 3rd .then() 在建立之前执行,并将特殊添加到数据库中。我需要先将 establishment 和 special 添加到数据库中,因为我需要获取它们的 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 链中,99% 的情况下,当你创建一个新的 Promise(通过 API 调用,或 new Promise 等)时,你应该 return 它,或者以其他方式将它与其他东西放在一起(例如 Promise.all 和 return that)。这意味着可以在更高级别处理可能的拒绝,并且意味着链中的 next .then 将仅在前一个 .then 完成后才开始.

每改变一次

Backendless.Data.of(

return Backendless.Data.of(

此外,您可能 想要在每个级别都成为 catch,就像您目前所做的那样 - 无论何时 catch,你将一个被拒绝的 Promise 变成一个已解决的 Promise,随后的 .thens 可能会 运行ning 假设之前的 .then 中的一切都成功完成。对于像这样的顺序异步操作,如果出现错误 任何地方,您可能想要停止整个过程,而不是尝试继续(这可能会导致错误)。

例如,如果 Backendless.Data.of('Establishment').save 失败,则 establishmentObjectId 永远不会被分配给,并且稍后在最后的 .then 中尝试使用它是行不通的。与 specialObjectId.

相同的事情

对于此代码,还有一个更好的模式可以遵循:与其使用两个单独的 .then,一个获取 establishmentObjectId,一个获取 specialObjectId,请考虑让这些操作 运行 并行,并在 Promise.all 完成后 运行 最后的 .then。大致如下:

const getEstablishmentObjectId = () => {
  //Get the add form data
  // ...
  //Create establishment from user's enteries
  var establishment = {
    // ...
  }
  //Save establishment to db
  return Backendless.Data.of('Establishment').save(establishment)
    .then(savedObject => savedObject.objectId);
};
const getSpecialObjectId = () => {
    // ...
    return Backendless.Data.of('Special').save(special)
      .then(savedObject => savedObject.objectId);
};

Promise.all([
  getEstablishmentObjectId(),
  getSpecialObjectId(),
]).then(([establishmentObjectId, specialObjectId]) => {
    console.log(establishmentObjectId);
    console.log(specialObjectId);
    var parentObject = {
      objectId: establishmentObjectId
    };
    // etc
  })
  .catch((error) => {
    console.log('Error', error);
  });