0

У меня есть это приложение, которое загружает файл на сервер с помощью $ cordovaFileTransfer, а затем отправляет данные о файле на тот же сервер. Файл передается штрафом. Затем данные отправляются на сервер, и сервер отвечает. Но ответ не возвращается к ответу на обещание. Зачем?Угловое обещание callback not firing

$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

Я I только один видя непарные скобки повсюду в коде? –

+0

спасибо @AbdoAdel ... добавил отсутствующие скобки. – lilbiscuit

ответ

4

$cordovaFileTransfer.upload возвращает обещание объект, который можно использовать для создания посыла механизм формирования цепочки.

Код

$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 
    }); 
} 
+0

безупречный. спасибо @pankaj. – lilbiscuit

+0

@lilbiscuit Рад помочь вам. Благодаря :-) –

1

его, потому что вы ретрансляция на другой Promise, обратного вызова, чтобы начать обещание и .. скорее всего, до того, как обещание инициализируется вы подключаете обратный вызов карапуз него .. поэтому на момент присоединения обратного вызова обещание еще не инициализировано, то есть 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 решение, хотя это лучший подход ...

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) { 

}); 
Смежные вопросы