你如何按特定顺序执行javascript函数?

时间:2015-04-10 11:36:51

标签: javascript node.js asynchronous frisby.js

编辑:我正在构建一些测试,向API提交POST请求,执行数据库查询,最后将数据库输出与API响应匹配,我有代码执行这些单独的任务但是如何按特定顺序执行javascript函数?

var frisby = require('frisby');
var oracledb = require('oracledb');
var url = require('endpoints.js');
var auth = require('users.js');
var dbConnect = require('dbconfig.js');

var myDetails = undefined;

function submitRequest(){
  frisby.create('Update contact details')
  .put(url.myAccount, {
    "addressLine-1": 'String',
    "addressLine-2": 'String',
    addressTown: 'String',
    addressCounty: 'String',
    addressPostcode: 'String',
    homePhone: 'String',
    mobilePhone: 'String'
  }, {json: true})
  .expectStatus(200)
  .expectHeaderContains('content-type', 'application/json')
  .auth(auth.username1, auth.password1)
.toss();
readDatabase();
}

function readDatabase(){
  oracledb.getConnection(
    {
      user          : dbConnect.user,
      password      : dbConnect.password,
      connectString : dbConnect.connectString
    },
    function(err, connection){
      if (err) {
        console.error(err.message);
        return;
      }
      connection.execute(
      "SELECT addressLine1, addressLine2, addressLine3, town, county, postcode, homePhone, mobilePhone"
      + "FROM addressDetails"
      + "WHERE accountNo = 1",

      function(err, result){
        if (err) {
          console.error(err.message);
          return;
        }
        myDetails = JSON.stringify(result.rows);
        myDetails = JSON.parse(myDetails);
    });
});
matchValues();
}

function matchValues(){
frisby.create('Match Database and API Values')
  .get(url.myAccount)
  .expectStatus(200)
  .expectHeaderContains('content-type', 'application/json')
  .auth(auth.username1, auth.password1)
  .afterJSON(function (body) {
    expect(body.addressLine1).toMatch(myDetails[0][0])
    expect(body.addressLine2).toMatch(myDetails[0][1])
    expect(body.addressLine3).toMatch(myDetails[0][2])
    expect(body.town).toMatch(myDetails[0][3])
    expect(body.county).toMatch(myDetails[0][4])
    expect(body.postcode).toMatch(myDetails[0][5])
    expect(body.homePhone).toMatch(myDetails[0][6])
    expect(body.mobilePhone).toMatch(myDetails[0][7])
  })
.toss();
}

submitRequest();

当我运行此测试时,测试有时会通过,有时会失败,因为代码并不总是按顺序执行。我按照建议进行了更改,但仍然遇到同样的问题,我发现很难为这种情况应用回调/承诺

0 个答案:

没有答案
相关问题