我遇到了一些问题$q.defer();
当我使用回调时,我的代码正在运行(视图已更新),但$q.defer();事实并非如此.
这是我的代码:
服务:
eventsApp.factory('eventData', function($http, $q) {
return {
getEvent: function(callback) {
var deferred = $q.defer();
$http({method: 'GET', url: '/node/nodejsserver/server.js'}).
success(function(data, status, headers, config){
//callback(data.event);
deferred.resolve(data.event);
console.log('status: ', status, ' data: ', data);
}).
error(function(data, status, headers, config){
deferred.reject(status);
console.log('status: ', status);
});
return deferred.promise;
}
};
});
Run Code Online (Sandbox Code Playgroud)
控制器:
eventsApp.controller('EventController',
function EventController($scope, eventData) {
$scope.event = eventData.getEvent();
}
);
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
然后我找到了这个答案,我更新了我的控制器,如下所示:
eventsApp.controller('EventController',
function EventController($scope, eventData) {
eventData.getEvent().then(function(result) { …Run Code Online (Sandbox Code Playgroud) 这样做可以吗?
例如,我有我的退出服务
logout: function() {
var defer = $q.defer();
this.getCustomer().then(function(credentials) {
$http.post(CONSTANT_VARS.BACKEND_URL + '/auth/logout',
{username: credentials.username, customer: credentials.customer}
).success(function(data) {
if (data.error) {
defer.reject(data);
}
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_CUSTOMER).then(function() {
/*Removing LocalForage Items*/
cleanLocalForage();
defer.resolve(data);
}, function(err) {
console.log(err);
defer.reject(data);
});
}).error(function(data) {
cleanLocalForage();
defer.reject(data);
});
}, function(err) {
defer.reject(err);
});
return defer.promise;
},
Run Code Online (Sandbox Code Playgroud)
然后我在控制器中有一个函数,一旦会话到期就会返回一个错误.当会话到期时,我需要注销用户并将其重定向到登录路径.所以,这就是我到目前为止所拥有的:
$scope.removeSlip = function(slip) {
BetSlipFactory.removeSlip(slip).then(function() {
}, function(err) {
console.log(err);
AuthFactory.logout();
$location.path('/');
});
};
Run Code Online (Sandbox Code Playgroud)
或者我应该通过注销承诺做这样的事情BetSlipFactory.removeSlip()吗?
$scope.removeSlip = function(slip) {
BetSlipFactory.removeSlip(slip).then(function() {
}, function(err) {
console.log(err);
AuthFactory.logout().then(function() …Run Code Online (Sandbox Code Playgroud) 以下代码返回:
output.isPending?: true
output.isRejected?: false
output.isFulfilled?: false
Run Code Online (Sandbox Code Playgroud)
为什么?我原以为output.isRejected是true.
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.7/q.js"></script>
<script src="http://jasmine.github.io/2.3/lib/jasmine.js"></script>
</head>
<body>
</body>
<script>
var output, bar;
bar = {
doSomethingAsync: function() {
var d = Q.defer();
d.resolve('result');
return d.promise;
}
};
function Foo(bar) {
this._bar = bar;
this.go = function() {
var deferred = Q.defer();
this._bar.doSomethingAsync()
.then(onSuccess.bind(this, deferred));
return deferred.promise;
}
};
function onSuccess(deferred, result) {
deferred.reject();
}
output = new Foo(bar).go()
.finally(function() {
console.log('output.isPending?:', output.isPending());
console.log('output.isRejected?:', output.isRejected());
console.log('output.isFulfilled?:', output.isFulfilled());
}); …Run Code Online (Sandbox Code Playgroud) 我有一个功能downloadItem可能会因网络原因而失败,我希望能够在实际拒绝该项目之前重试几次。重试需要超时,因为如果出现网络问题,则立即重试是没有意义的。
这是我到目前为止所拥有的:
function downloadItemWithRetryAndTimeout(url, retry, failedReason) {
return new Promise(function(resolve, reject) {
try {
if (retry < 0 && failedReason != null) reject(failedReason);
downloadItem(url);
resolve();
} catch (e) {
setTimeout(function() {
downloadItemWithRetryAndTimeout(url, retry - 1, e);
}, 1000);
}
});
}
Run Code Online (Sandbox Code Playgroud)
显然,这会失败,因为我第二次(以及第二次)打电话时,downloadItemWithRetryAndTimeout我没有按要求返回承诺。
我如何让它与第二个承诺一起正常工作?
PS,如果代码在 NodeJS 中运行很重要。
我什么时候应该使用哪个?以下是相同的吗?
新的Promise()示例:
function multiRejectExample(){
return new Promise(function (resolve, reject){
if(statement){
console.log('statement 1');
reject(throw new Error('error'));
}
if(statement){
console.log('statement 2');
reject(throw new Error('error'));
}
});
}
Run Code Online (Sandbox Code Playgroud)
Promise.try()示例:
function tryExample(){
return Promise.try(function(){
if(statement){
console.log('statement 1');
throw new Error('error');
}
if(statement){
console.log('statement 2');
throw new Error('error');
}
});
}
Run Code Online (Sandbox Code Playgroud) 所以我试图将我的代码转移到"Promise world",并且在很多地方,当我不得不"循环"异步功能时 - 我只是以这种方式使用递归
function doRecursion(idx,callback){
if(idx < someArray.length){
doAsync(function(){
doRecursion(++idx,callback)
});
}else{
callback('done!')
}
}
doRecursion(0,function(msg){
//...
});
Run Code Online (Sandbox Code Playgroud)
现在我正试图改变进入Promise世界,我很困惑
var Promise = require('bluebird')
function doRecursion(idx){
return new Promise(function(resolve){
if(idx < someArray.length){
doAsync(function(){
//... doRecursion(++idx)
// how do i call doRecusion here....
});
}else{
resolve('done!')
}
});
}
doRecursion(0).then(function(msg){
//...
});
Run Code Online (Sandbox Code Playgroud)
谢谢.
所以我正在制作一个用于学习目的的小爬虫,最终我应该得到网站上页面的树状结构。
我一直在绞尽脑汁试图让这些要求正确。这或多或少是我所拥有的:
var request = require('request');
function scanPage(url) {
// request the page at given url:
request.get(url, function(err, res, body) {
var pageObject = {};
/* [... Jquery mumbo-jumbo to
1. Fill the page object with information and
2. Get the links on that page and store them into arrayOfLinks
*/
var arrayOfLinks = ['url1', 'url2', 'url3'];
for (var i = 0; i < arrayOfLinks.length; i++) {
pageObj[arrayOfLinks[i]] = scanPage[arrayOfLinks[i]];
}
});
return pageObj;
}
Run Code Online (Sandbox Code Playgroud)
我知道这段代码在很多层面上都是错误的,但它应该让您了解我正在尝试做什么。
我应该如何修改它才能使其正常工作?(如果可能的话,不使用承诺)
(您可以假设该网站具有树状结构,因此每个页面仅具有指向三个页面下方页面的链接,因此采用递归方法)
我知道在Nodejs / Express中兑现承诺的最佳方法是:
doSomeThing()
.then()
.then()
.catch();
Run Code Online (Sandbox Code Playgroud)
但是最近不得不使用async和q模块来遍历列表/数组并运行async函数。我想知道这样做/编写此方法的更好方法-
var deferred = Q.defer();
var deferred2 = Q.defer();
models.Local.findOne({
where: {
id: parseInt(req.body.localid)
}
})
.then(function(resultLocal){
if(!resultLocal){
return res.status(404).json(
{
"status" : "error",
'error': "Local Not Found"
});
}
return models.Documents.create(req.body.document);
})
.then(function(docCreated){
var attributes = req.body.document.Attributes;
async.each(attributes, function(item, callback) {
models.Doc_Tags.create({
value: item.value,
attribute_id: item.id,
document_id: docCreated.id
})
.then(function(attributeCreated){
var upObj = {};
upObj[item.col_name] = item.value;
models[item.table_name].update(upObj,{
where:{
id: req.body.document.local_id
}
})
.then(function(primaryUpdated){
deferred2.resolve();
})
.catch(function(error){
return res.status(400).json({status: 'error', error:error.message});
}); …Run Code Online (Sandbox Code Playgroud) 我正在使用fetch.js(https://github.com/github/fetch)将相对较大的json对象发送到后端。json很大,因为它包含SVG图片字符串。
我不清楚默认情况下fetch.js是否使用gzip压缩,或者是否需要手动压缩并添加标头。任何帮助,将不胜感激。
return new Promise((resolve, reject) => {
fetch(api_base + "/api/save-photo", {
method: 'POST',
mode : 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
})
.then((response) => {
if (response.status === 404) {
throw new Error('404 (Not Found)');
} else {
return response.json().then((json) => {
console.log('save poster response: ', json);
return json;
});
}
})
我有一个函数,它将一个对象传递给它,其中键和数据是一个数组.我必须调用API来获取附加信息,然后将其添加回对象并返回整个对象.
我的第一种方法是不正确的,因为我试图将数据传出.then(),但这是错误的做法.
function asignChecklistItems(taskArray) {
// get all the people's tasks passed in
return new Promise(function(resolve, reject) {
var promises = []
// Task Array: {"Person":[tasks,tasks,tasks]}
for (var person in taskArray) {
var individualTaskPerson = taskArray[person]
// get the person's tasks
for (var individualTask in individualTaskPerson) {
// here we get each individual task
var task = individualTaskPerson[individualTask]
// Check if the checklist is present, the .exists is a bool
if (task.checklist.exists === true) {
//Here we push …Run Code Online (Sandbox Code Playgroud) javascript ×10
promise ×7
node.js ×5
angularjs ×2
asynchronous ×2
q ×2
bluebird ×1
es6-promise ×1
express ×1
fetch ×1
gzip ×1
json ×1
recursion ×1
settimeout ×1
web-scraping ×1