如何在REST API中使用AJAX的fetch方法? 任何一个例子。
我尝试使用
fetch('https://jsonplaceholder.typicode.com/posts').then( (r) => console.log( r ));

并没有按预期获得JSON。
答案 0 :(得分:1)
您应该在JSON中转换promise结果。尝试使用
class CommonTests: XCTestCase {
var validate: XCTestExpectation? = nil
func testMytest() {
validate(completion: {
loadSomeStuff(completion: { (list: [Stuff]?) in
// actual test
}
})
}
func validate(completion: @escaping ()->()) {
self.validateExpectation = self.expectation(description: "Setup")
// async operation can be fired here
// or if already started from somewhere else just wait for it to complete
self.waitForExpectations(timeout: 60) { (error: Error?) in
XCTAssert((error == nil), error?.localizedDescription ?? "Failed with unknown error")
completion()
}
}
func validateAsyncCompleted() {
self.validateExpectation?.fulfill()
}
func loadStuff(completion: @escaping ([Stuff]?)->()) {
// possible place for assertion or some other checks
let expectation = self.expectation(description: "loading")
DispatchQueue.global().async {
let result: [Stuff]? = nil
// load operation
expectation.fulfill()
completion(result)
}
self.waitForExpectations(timeout: 90) { (error: Error?) in
XCTAssert((error == nil), error?.localizedDescription ?? "load - failed with unknown error")
}
}
}