我有这个应用程序使用$ cordovaFileTransfer将文件上传到服务器,然后将有关该文件的数据发送到同一服务器。文件传输正常。然后将数据发送到服务器,服务器响应。但是响应并没有让它回到承诺回调。为什么呢?
$scope.sendPost = function(data) {
//first upload a file then send more data about the file
$cordovaFileTransfer.upload('http://example.com', 'myfile.txt', options)
.then(function(result) {
var promise = MyFactory.sendFileData(data);
});
promise.then(function(response) {
//we never make it to here
});
}
并在MyFactory中:
service.sendFileData = function(data) {
return $http({
//bunch of parameters. This function works, data is sent to the server and a response received
}).then(function(response) {
//this is fired when the response is received from the server. All is good so far.
return.response.data
});
}
return service;
答案 0 :(得分:4)
$cordovaFileTransfer.upload
返回一个promise对象,您可以使用该对象构建promise链接机制。
<强>代码强>
$scope.sendPost = function(data) {
//get hold on `upload` function promise
var promise = $cordovaFileTransfer.upload('http://example.com', 'myfile.txt', options)
.then(function(result)) {
//return MyFactory.sendFileData promise here which will follow promise chaining
return MyFactory.sendFileData(data);
});
//promise.then will get call once `MyFactory.sendFileData` complete it
promise.then(function(response) {
//will get called once `sendFileData` complete its promise
});
}
答案 1 :(得分:1)
因为您正在转发另一个 承诺 回调以启动承诺,并且...很可能在承诺初始化之前您附加一个回调它...所以在你附加回调时,承诺尚未初始化,即promise
是null
..所以在你的控制台中你会看到一个错误。
尝试做一些像
这样的事情var x = function(response) {
//we'll make it to here now...
}
$cordovaFileTransfer.upload('http://example.com', 'myfile.txt', options)
.then(function(result)) {
var promise = MyFactory.sendFileData(data);
promise.then(x);
});
你应该遵循@PankajParkar解决方案,虽然这是一个更好的方法......
答案 2 :(得分:0)
$scope.sendPost = function(data) {
//first upload a file then send more data about the file
$cordovaFileTransfer.upload('http://example.com', 'myfile.txt', options)
.then(function(result)) {
return MyFactory.sendFileData(result.data);
})
.then(function(response) {
});