我正在尝试使用量角器调用api - 它会向我返回一些JSON,我想断言它。我以为我有这个工作,直到我试图进一步,并意识到我没有做对,但有一点时间试图找出原因。
我已经放置了一些console.logs并且预期序列为1,2,3但是它看起来是3(测试完成)然后是2和1.所以我怀疑是一个承诺问题。
以下代码:
'use strict';
var request = require('request');
var path = require('path');
var info;
//var fname = null;
var fname = 'joe';
describe("Sample test", function() {
var request = require('request');
var options = {
method: 'GET',
url: 'URL here',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: '{ "pay_load": [] }'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
info = JSON.parse(body);
console.log('in the callback now');
//console.log('body :' + body);
//var count = Object.keys(info).length;
//console.log('body len:' + count);
//console.log('info :' + info);
fname = info.firstname;
console.log('firstname1 : ' + info.firstname);
console.log('firstname2 : ' + fname);
} else {
console.log('there was some error');
}
}
it("proves the API is alive - firstname is null", function() {
request(options, callback);
//expect(fname).toBe(null);
console.log('firstname3 : ' + fname);
//expect(fname).toBe(null);
//var common = new Common();
//common.checkForAPI();
});
所以在我的脑海里,我以为我会看到“在回调中”,然后是“firstname1”,“firstname2”,最后是“firstname3”
答案 0 :(得分:0)
不,firstname3
将始终以您拥有的方式首先打印。因为nodejs中的所有http请求都是异步的原因,所以当您的请求正在处理(或在飞行中)时,将打印firstname3
。然后在您的请求回调中调用console.logs。
简单的例子,它将按顺序打印firstname1,2,3(已测试)
var request = function(cb) {
//basically call your request stuff and then when you are done call cb
console.log('firstname 1');
console.log('firstname 2');
cb();
};
request(function() {
console.log('firstname 3');
});
打印
firstname 1
firstname 2
firstname 3
或者您可以使用名为async的第三方库并使用async.tryEach来串行运行任务。
async.tryEach([
function getDataFromFirstWebsite(callback) {
// Try getting the data from the first website
callback(err, data);
},
function getDataFromSecondWebsite(callback) {
// First website failed,
// Try getting the data from the backup website
callback(err, data);
}
],
// optional callback
function(err, results) {
Now do something with the data.
});